1
0

first gen

This commit is contained in:
syui 2022-08-31 16:49:08 +09:00 committed by syui
parent d40e30944b
commit 22734a4b4c
Signed by: syui
GPG Key ID: 5417CFEBAD92DF56
89 changed files with 25861 additions and 16973 deletions

181
ent/card.go Normal file
View File

@ -0,0 +1,181 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"t/ent/card"
"t/ent/user"
"time"
"entgo.io/ent/dialect/sql"
)
// Card is the model entity for the Card schema.
type Card struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Card holds the value of the "card" field.
Card int `json:"card,omitempty"`
// Status holds the value of the "status" field.
Status string `json:"status,omitempty"`
// Cp holds the value of the "cp" field.
Cp int `json:"cp,omitempty"`
// URL holds the value of the "url" field.
URL string `json:"url,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the CardQuery when eager-loading is set.
Edges CardEdges `json:"edges"`
user_card *int
}
// CardEdges holds the relations/edges for other nodes in the graph.
type CardEdges struct {
// Owner holds the value of the owner edge.
Owner *User `json:"owner,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// OwnerOrErr returns the Owner value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e CardEdges) OwnerOrErr() (*User, error) {
if e.loadedTypes[0] {
if e.Owner == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: user.Label}
}
return e.Owner, nil
}
return nil, &NotLoadedError{edge: "owner"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Card) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case card.FieldID, card.FieldCard, card.FieldCp:
values[i] = new(sql.NullInt64)
case card.FieldStatus, card.FieldURL:
values[i] = new(sql.NullString)
case card.FieldCreatedAt:
values[i] = new(sql.NullTime)
case card.ForeignKeys[0]: // user_card
values[i] = new(sql.NullInt64)
default:
return nil, fmt.Errorf("unexpected column %q for type Card", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Card fields.
func (c *Card) 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 card.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
c.ID = int(value.Int64)
case card.FieldCard:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field card", values[i])
} else if value.Valid {
c.Card = int(value.Int64)
}
case card.FieldStatus:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field status", values[i])
} else if value.Valid {
c.Status = value.String
}
case card.FieldCp:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field cp", values[i])
} else if value.Valid {
c.Cp = int(value.Int64)
}
case card.FieldURL:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field url", values[i])
} else if value.Valid {
c.URL = value.String
}
case card.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 {
c.CreatedAt = value.Time
}
case card.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for edge-field user_card", value)
} else if value.Valid {
c.user_card = new(int)
*c.user_card = int(value.Int64)
}
}
}
return nil
}
// QueryOwner queries the "owner" edge of the Card entity.
func (c *Card) QueryOwner() *UserQuery {
return NewCardClient(c.config).QueryOwner(c)
}
// Update returns a builder for updating this Card.
// Note that you need to call Card.Unwrap() before calling this method if this Card
// was returned from a transaction, and the transaction was committed or rolled back.
func (c *Card) Update() *CardUpdateOne {
return NewCardClient(c.config).UpdateOne(c)
}
// Unwrap unwraps the Card 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 (c *Card) Unwrap() *Card {
_tx, ok := c.config.driver.(*txDriver)
if !ok {
panic("ent: Card is not a transactional entity")
}
c.config.driver = _tx.drv
return c
}
// String implements the fmt.Stringer.
func (c *Card) String() string {
var builder strings.Builder
builder.WriteString("Card(")
builder.WriteString(fmt.Sprintf("id=%v, ", c.ID))
builder.WriteString("card=")
builder.WriteString(fmt.Sprintf("%v", c.Card))
builder.WriteString(", ")
builder.WriteString("status=")
builder.WriteString(c.Status)
builder.WriteString(", ")
builder.WriteString("cp=")
builder.WriteString(fmt.Sprintf("%v", c.Cp))
builder.WriteString(", ")
builder.WriteString("url=")
builder.WriteString(c.URL)
builder.WriteString(", ")
builder.WriteString("created_at=")
builder.WriteString(c.CreatedAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// Cards is a parsable slice of Card.
type Cards []*Card

79
ent/card/card.go Normal file
View File

@ -0,0 +1,79 @@
// Code generated by ent, DO NOT EDIT.
package card
import (
"time"
)
const (
// Label holds the string label denoting the card type in the database.
Label = "card"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCard holds the string denoting the card field in the database.
FieldCard = "card"
// FieldStatus holds the string denoting the status field in the database.
FieldStatus = "status"
// FieldCp holds the string denoting the cp field in the database.
FieldCp = "cp"
// FieldURL holds the string denoting the url field in the database.
FieldURL = "url"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// EdgeOwner holds the string denoting the owner edge name in mutations.
EdgeOwner = "owner"
// Table holds the table name of the card in the database.
Table = "cards"
// OwnerTable is the table that holds the owner relation/edge.
OwnerTable = "cards"
// OwnerInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
OwnerInverseTable = "users"
// OwnerColumn is the table column denoting the owner relation/edge.
OwnerColumn = "user_card"
)
// Columns holds all SQL columns for card fields.
var Columns = []string{
FieldID,
FieldCard,
FieldStatus,
FieldCp,
FieldURL,
FieldCreatedAt,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "cards"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"user_card",
}
// 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 (
// DefaultCard holds the default value on creation for the "card" field.
DefaultCard func() int
// DefaultStatus holds the default value on creation for the "status" field.
DefaultStatus func() string
// DefaultCp holds the default value on creation for the "cp" field.
DefaultCp func() int
// DefaultURL holds the default value on creation for the "url" field.
DefaultURL string
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
)

440
ent/card/where.go Normal file
View File

@ -0,0 +1,440 @@
// Code generated by ent, DO NOT EDIT.
package card
import (
"t/ent/predicate"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Card {
return predicate.Card(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Card {
return predicate.Card(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Card {
return predicate.Card(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldID, id))
}
// Card applies equality check predicate on the "card" field. It's identical to CardEQ.
func Card(v int) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldCard, v))
}
// Status applies equality check predicate on the "status" field. It's identical to StatusEQ.
func Status(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldStatus, v))
}
// Cp applies equality check predicate on the "cp" field. It's identical to CpEQ.
func Cp(v int) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldCp, v))
}
// URL applies equality check predicate on the "url" field. It's identical to URLEQ.
func URL(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldURL, v))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldCreatedAt, v))
}
// CardEQ applies the EQ predicate on the "card" field.
func CardEQ(v int) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldCard, v))
}
// CardNEQ applies the NEQ predicate on the "card" field.
func CardNEQ(v int) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldCard, v))
}
// CardIn applies the In predicate on the "card" field.
func CardIn(vs ...int) predicate.Card {
return predicate.Card(sql.FieldIn(FieldCard, vs...))
}
// CardNotIn applies the NotIn predicate on the "card" field.
func CardNotIn(vs ...int) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldCard, vs...))
}
// CardGT applies the GT predicate on the "card" field.
func CardGT(v int) predicate.Card {
return predicate.Card(sql.FieldGT(FieldCard, v))
}
// CardGTE applies the GTE predicate on the "card" field.
func CardGTE(v int) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldCard, v))
}
// CardLT applies the LT predicate on the "card" field.
func CardLT(v int) predicate.Card {
return predicate.Card(sql.FieldLT(FieldCard, v))
}
// CardLTE applies the LTE predicate on the "card" field.
func CardLTE(v int) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldCard, v))
}
// CardIsNil applies the IsNil predicate on the "card" field.
func CardIsNil() predicate.Card {
return predicate.Card(sql.FieldIsNull(FieldCard))
}
// CardNotNil applies the NotNil predicate on the "card" field.
func CardNotNil() predicate.Card {
return predicate.Card(sql.FieldNotNull(FieldCard))
}
// StatusEQ applies the EQ predicate on the "status" field.
func StatusEQ(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldStatus, v))
}
// StatusNEQ applies the NEQ predicate on the "status" field.
func StatusNEQ(v string) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldStatus, v))
}
// StatusIn applies the In predicate on the "status" field.
func StatusIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldIn(FieldStatus, vs...))
}
// StatusNotIn applies the NotIn predicate on the "status" field.
func StatusNotIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldStatus, vs...))
}
// StatusGT applies the GT predicate on the "status" field.
func StatusGT(v string) predicate.Card {
return predicate.Card(sql.FieldGT(FieldStatus, v))
}
// StatusGTE applies the GTE predicate on the "status" field.
func StatusGTE(v string) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldStatus, v))
}
// StatusLT applies the LT predicate on the "status" field.
func StatusLT(v string) predicate.Card {
return predicate.Card(sql.FieldLT(FieldStatus, v))
}
// StatusLTE applies the LTE predicate on the "status" field.
func StatusLTE(v string) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldStatus, v))
}
// StatusContains applies the Contains predicate on the "status" field.
func StatusContains(v string) predicate.Card {
return predicate.Card(sql.FieldContains(FieldStatus, v))
}
// StatusHasPrefix applies the HasPrefix predicate on the "status" field.
func StatusHasPrefix(v string) predicate.Card {
return predicate.Card(sql.FieldHasPrefix(FieldStatus, v))
}
// StatusHasSuffix applies the HasSuffix predicate on the "status" field.
func StatusHasSuffix(v string) predicate.Card {
return predicate.Card(sql.FieldHasSuffix(FieldStatus, v))
}
// StatusIsNil applies the IsNil predicate on the "status" field.
func StatusIsNil() predicate.Card {
return predicate.Card(sql.FieldIsNull(FieldStatus))
}
// StatusNotNil applies the NotNil predicate on the "status" field.
func StatusNotNil() predicate.Card {
return predicate.Card(sql.FieldNotNull(FieldStatus))
}
// StatusEqualFold applies the EqualFold predicate on the "status" field.
func StatusEqualFold(v string) predicate.Card {
return predicate.Card(sql.FieldEqualFold(FieldStatus, v))
}
// StatusContainsFold applies the ContainsFold predicate on the "status" field.
func StatusContainsFold(v string) predicate.Card {
return predicate.Card(sql.FieldContainsFold(FieldStatus, v))
}
// CpEQ applies the EQ predicate on the "cp" field.
func CpEQ(v int) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldCp, v))
}
// CpNEQ applies the NEQ predicate on the "cp" field.
func CpNEQ(v int) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldCp, v))
}
// CpIn applies the In predicate on the "cp" field.
func CpIn(vs ...int) predicate.Card {
return predicate.Card(sql.FieldIn(FieldCp, vs...))
}
// CpNotIn applies the NotIn predicate on the "cp" field.
func CpNotIn(vs ...int) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldCp, vs...))
}
// CpGT applies the GT predicate on the "cp" field.
func CpGT(v int) predicate.Card {
return predicate.Card(sql.FieldGT(FieldCp, v))
}
// CpGTE applies the GTE predicate on the "cp" field.
func CpGTE(v int) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldCp, v))
}
// CpLT applies the LT predicate on the "cp" field.
func CpLT(v int) predicate.Card {
return predicate.Card(sql.FieldLT(FieldCp, v))
}
// CpLTE applies the LTE predicate on the "cp" field.
func CpLTE(v int) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldCp, v))
}
// CpIsNil applies the IsNil predicate on the "cp" field.
func CpIsNil() predicate.Card {
return predicate.Card(sql.FieldIsNull(FieldCp))
}
// CpNotNil applies the NotNil predicate on the "cp" field.
func CpNotNil() predicate.Card {
return predicate.Card(sql.FieldNotNull(FieldCp))
}
// URLEQ applies the EQ predicate on the "url" field.
func URLEQ(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldURL, v))
}
// URLNEQ applies the NEQ predicate on the "url" field.
func URLNEQ(v string) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldURL, v))
}
// URLIn applies the In predicate on the "url" field.
func URLIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldIn(FieldURL, vs...))
}
// URLNotIn applies the NotIn predicate on the "url" field.
func URLNotIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldURL, vs...))
}
// URLGT applies the GT predicate on the "url" field.
func URLGT(v string) predicate.Card {
return predicate.Card(sql.FieldGT(FieldURL, v))
}
// URLGTE applies the GTE predicate on the "url" field.
func URLGTE(v string) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldURL, v))
}
// URLLT applies the LT predicate on the "url" field.
func URLLT(v string) predicate.Card {
return predicate.Card(sql.FieldLT(FieldURL, v))
}
// URLLTE applies the LTE predicate on the "url" field.
func URLLTE(v string) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldURL, v))
}
// URLContains applies the Contains predicate on the "url" field.
func URLContains(v string) predicate.Card {
return predicate.Card(sql.FieldContains(FieldURL, v))
}
// URLHasPrefix applies the HasPrefix predicate on the "url" field.
func URLHasPrefix(v string) predicate.Card {
return predicate.Card(sql.FieldHasPrefix(FieldURL, v))
}
// URLHasSuffix applies the HasSuffix predicate on the "url" field.
func URLHasSuffix(v string) predicate.Card {
return predicate.Card(sql.FieldHasSuffix(FieldURL, v))
}
// URLIsNil applies the IsNil predicate on the "url" field.
func URLIsNil() predicate.Card {
return predicate.Card(sql.FieldIsNull(FieldURL))
}
// URLNotNil applies the NotNil predicate on the "url" field.
func URLNotNil() predicate.Card {
return predicate.Card(sql.FieldNotNull(FieldURL))
}
// URLEqualFold applies the EqualFold predicate on the "url" field.
func URLEqualFold(v string) predicate.Card {
return predicate.Card(sql.FieldEqualFold(FieldURL, v))
}
// URLContainsFold applies the ContainsFold predicate on the "url" field.
func URLContainsFold(v string) predicate.Card {
return predicate.Card(sql.FieldContainsFold(FieldURL, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.Card {
return predicate.Card(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.Card {
return predicate.Card(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.Card {
return predicate.Card(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldCreatedAt, v))
}
// CreatedAtIsNil applies the IsNil predicate on the "created_at" field.
func CreatedAtIsNil() predicate.Card {
return predicate.Card(sql.FieldIsNull(FieldCreatedAt))
}
// CreatedAtNotNil applies the NotNil predicate on the "created_at" field.
func CreatedAtNotNil() predicate.Card {
return predicate.Card(sql.FieldNotNull(FieldCreatedAt))
}
// HasOwner applies the HasEdge predicate on the "owner" edge.
func HasOwner() predicate.Card {
return predicate.Card(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasOwnerWith applies the HasEdge predicate on the "owner" edge with a given conditions (other predicates).
func HasOwnerWith(preds ...predicate.User) predicate.Card {
return predicate.Card(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(OwnerInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
)
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.Card) predicate.Card {
return predicate.Card(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Card) predicate.Card {
return predicate.Card(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Card) predicate.Card {
return predicate.Card(func(s *sql.Selector) {
p(s.Not())
})
}

318
ent/card_create.go Normal file
View File

@ -0,0 +1,318 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"t/ent/card"
"t/ent/user"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// CardCreate is the builder for creating a Card entity.
type CardCreate struct {
config
mutation *CardMutation
hooks []Hook
}
// SetCard sets the "card" field.
func (cc *CardCreate) SetCard(i int) *CardCreate {
cc.mutation.SetCard(i)
return cc
}
// SetNillableCard sets the "card" field if the given value is not nil.
func (cc *CardCreate) SetNillableCard(i *int) *CardCreate {
if i != nil {
cc.SetCard(*i)
}
return cc
}
// SetStatus sets the "status" field.
func (cc *CardCreate) SetStatus(s string) *CardCreate {
cc.mutation.SetStatus(s)
return cc
}
// SetNillableStatus sets the "status" field if the given value is not nil.
func (cc *CardCreate) SetNillableStatus(s *string) *CardCreate {
if s != nil {
cc.SetStatus(*s)
}
return cc
}
// SetCp sets the "cp" field.
func (cc *CardCreate) SetCp(i int) *CardCreate {
cc.mutation.SetCp(i)
return cc
}
// SetNillableCp sets the "cp" field if the given value is not nil.
func (cc *CardCreate) SetNillableCp(i *int) *CardCreate {
if i != nil {
cc.SetCp(*i)
}
return cc
}
// SetURL sets the "url" field.
func (cc *CardCreate) SetURL(s string) *CardCreate {
cc.mutation.SetURL(s)
return cc
}
// SetNillableURL sets the "url" field if the given value is not nil.
func (cc *CardCreate) SetNillableURL(s *string) *CardCreate {
if s != nil {
cc.SetURL(*s)
}
return cc
}
// SetCreatedAt sets the "created_at" field.
func (cc *CardCreate) SetCreatedAt(t time.Time) *CardCreate {
cc.mutation.SetCreatedAt(t)
return cc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (cc *CardCreate) SetNillableCreatedAt(t *time.Time) *CardCreate {
if t != nil {
cc.SetCreatedAt(*t)
}
return cc
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (cc *CardCreate) SetOwnerID(id int) *CardCreate {
cc.mutation.SetOwnerID(id)
return cc
}
// SetOwner sets the "owner" edge to the User entity.
func (cc *CardCreate) SetOwner(u *User) *CardCreate {
return cc.SetOwnerID(u.ID)
}
// Mutation returns the CardMutation object of the builder.
func (cc *CardCreate) Mutation() *CardMutation {
return cc.mutation
}
// Save creates the Card in the database.
func (cc *CardCreate) Save(ctx context.Context) (*Card, error) {
cc.defaults()
return withHooks[*Card, CardMutation](ctx, cc.sqlSave, cc.mutation, cc.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (cc *CardCreate) SaveX(ctx context.Context) *Card {
v, err := cc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (cc *CardCreate) Exec(ctx context.Context) error {
_, err := cc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (cc *CardCreate) ExecX(ctx context.Context) {
if err := cc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (cc *CardCreate) defaults() {
if _, ok := cc.mutation.Card(); !ok {
v := card.DefaultCard()
cc.mutation.SetCard(v)
}
if _, ok := cc.mutation.Status(); !ok {
v := card.DefaultStatus()
cc.mutation.SetStatus(v)
}
if _, ok := cc.mutation.Cp(); !ok {
v := card.DefaultCp()
cc.mutation.SetCp(v)
}
if _, ok := cc.mutation.URL(); !ok {
v := card.DefaultURL
cc.mutation.SetURL(v)
}
if _, ok := cc.mutation.CreatedAt(); !ok {
v := card.DefaultCreatedAt()
cc.mutation.SetCreatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (cc *CardCreate) check() error {
if _, ok := cc.mutation.OwnerID(); !ok {
return &ValidationError{Name: "owner", err: errors.New(`ent: missing required edge "Card.owner"`)}
}
return nil
}
func (cc *CardCreate) sqlSave(ctx context.Context) (*Card, error) {
if err := cc.check(); err != nil {
return nil, err
}
_node, _spec := cc.createSpec()
if err := sqlgraph.CreateNode(ctx, cc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
cc.mutation.id = &_node.ID
cc.mutation.done = true
return _node, nil
}
func (cc *CardCreate) createSpec() (*Card, *sqlgraph.CreateSpec) {
var (
_node = &Card{config: cc.config}
_spec = sqlgraph.NewCreateSpec(card.Table, sqlgraph.NewFieldSpec(card.FieldID, field.TypeInt))
)
if value, ok := cc.mutation.Card(); ok {
_spec.SetField(card.FieldCard, field.TypeInt, value)
_node.Card = value
}
if value, ok := cc.mutation.Status(); ok {
_spec.SetField(card.FieldStatus, field.TypeString, value)
_node.Status = value
}
if value, ok := cc.mutation.Cp(); ok {
_spec.SetField(card.FieldCp, field.TypeInt, value)
_node.Cp = value
}
if value, ok := cc.mutation.URL(); ok {
_spec.SetField(card.FieldURL, field.TypeString, value)
_node.URL = value
}
if value, ok := cc.mutation.CreatedAt(); ok {
_spec.SetField(card.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
if nodes := cc.mutation.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: card.OwnerTable,
Columns: []string{card.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: user.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.user_card = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// CardCreateBulk is the builder for creating many Card entities in bulk.
type CardCreateBulk struct {
config
builders []*CardCreate
}
// Save creates the Card entities in the database.
func (ccb *CardCreateBulk) Save(ctx context.Context) ([]*Card, error) {
specs := make([]*sqlgraph.CreateSpec, len(ccb.builders))
nodes := make([]*Card, len(ccb.builders))
mutators := make([]Mutator, len(ccb.builders))
for i := range ccb.builders {
func(i int, root context.Context) {
builder := ccb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*CardMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, ccb.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, ccb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, ccb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (ccb *CardCreateBulk) SaveX(ctx context.Context) []*Card {
v, err := ccb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (ccb *CardCreateBulk) Exec(ctx context.Context) error {
_, err := ccb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ccb *CardCreateBulk) ExecX(ctx context.Context) {
if err := ccb.Exec(ctx); err != nil {
panic(err)
}
}

88
ent/card_delete.go Normal file
View File

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

613
ent/card_query.go Normal file
View File

@ -0,0 +1,613 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"t/ent/card"
"t/ent/predicate"
"t/ent/user"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// CardQuery is the builder for querying Card entities.
type CardQuery struct {
config
ctx *QueryContext
order []OrderFunc
inters []Interceptor
predicates []predicate.Card
withOwner *UserQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the CardQuery builder.
func (cq *CardQuery) Where(ps ...predicate.Card) *CardQuery {
cq.predicates = append(cq.predicates, ps...)
return cq
}
// Limit the number of records to be returned by this query.
func (cq *CardQuery) Limit(limit int) *CardQuery {
cq.ctx.Limit = &limit
return cq
}
// Offset to start from.
func (cq *CardQuery) Offset(offset int) *CardQuery {
cq.ctx.Offset = &offset
return cq
}
// 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 (cq *CardQuery) Unique(unique bool) *CardQuery {
cq.ctx.Unique = &unique
return cq
}
// Order specifies how the records should be ordered.
func (cq *CardQuery) Order(o ...OrderFunc) *CardQuery {
cq.order = append(cq.order, o...)
return cq
}
// QueryOwner chains the current query on the "owner" edge.
func (cq *CardQuery) QueryOwner() *UserQuery {
query := (&UserClient{config: cq.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := cq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := cq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(card.Table, card.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, card.OwnerTable, card.OwnerColumn),
)
fromU = sqlgraph.SetNeighbors(cq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Card entity from the query.
// Returns a *NotFoundError when no Card was found.
func (cq *CardQuery) First(ctx context.Context) (*Card, error) {
nodes, err := cq.Limit(1).All(setContextOp(ctx, cq.ctx, "First"))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{card.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (cq *CardQuery) FirstX(ctx context.Context) *Card {
node, err := cq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Card ID from the query.
// Returns a *NotFoundError when no Card ID was found.
func (cq *CardQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = cq.Limit(1).IDs(setContextOp(ctx, cq.ctx, "FirstID")); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{card.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (cq *CardQuery) FirstIDX(ctx context.Context) int {
id, err := cq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Card entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Card entity is found.
// Returns a *NotFoundError when no Card entities are found.
func (cq *CardQuery) Only(ctx context.Context) (*Card, error) {
nodes, err := cq.Limit(2).All(setContextOp(ctx, cq.ctx, "Only"))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{card.Label}
default:
return nil, &NotSingularError{card.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (cq *CardQuery) OnlyX(ctx context.Context) *Card {
node, err := cq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Card ID in the query.
// Returns a *NotSingularError when more than one Card ID is found.
// Returns a *NotFoundError when no entities are found.
func (cq *CardQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = cq.Limit(2).IDs(setContextOp(ctx, cq.ctx, "OnlyID")); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{card.Label}
default:
err = &NotSingularError{card.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (cq *CardQuery) OnlyIDX(ctx context.Context) int {
id, err := cq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Cards.
func (cq *CardQuery) All(ctx context.Context) ([]*Card, error) {
ctx = setContextOp(ctx, cq.ctx, "All")
if err := cq.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Card, *CardQuery]()
return withInterceptors[[]*Card](ctx, cq, qr, cq.inters)
}
// AllX is like All, but panics if an error occurs.
func (cq *CardQuery) AllX(ctx context.Context) []*Card {
nodes, err := cq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Card IDs.
func (cq *CardQuery) IDs(ctx context.Context) (ids []int, err error) {
if cq.ctx.Unique == nil && cq.path != nil {
cq.Unique(true)
}
ctx = setContextOp(ctx, cq.ctx, "IDs")
if err = cq.Select(card.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (cq *CardQuery) IDsX(ctx context.Context) []int {
ids, err := cq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (cq *CardQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, cq.ctx, "Count")
if err := cq.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, cq, querierCount[*CardQuery](), cq.inters)
}
// CountX is like Count, but panics if an error occurs.
func (cq *CardQuery) CountX(ctx context.Context) int {
count, err := cq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (cq *CardQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, cq.ctx, "Exist")
switch _, err := cq.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 (cq *CardQuery) ExistX(ctx context.Context) bool {
exist, err := cq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the CardQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (cq *CardQuery) Clone() *CardQuery {
if cq == nil {
return nil
}
return &CardQuery{
config: cq.config,
ctx: cq.ctx.Clone(),
order: append([]OrderFunc{}, cq.order...),
inters: append([]Interceptor{}, cq.inters...),
predicates: append([]predicate.Card{}, cq.predicates...),
withOwner: cq.withOwner.Clone(),
// clone intermediate query.
sql: cq.sql.Clone(),
path: cq.path,
}
}
// WithOwner tells the query-builder to eager-load the nodes that are connected to
// the "owner" edge. The optional arguments are used to configure the query builder of the edge.
func (cq *CardQuery) WithOwner(opts ...func(*UserQuery)) *CardQuery {
query := (&UserClient{config: cq.config}).Query()
for _, opt := range opts {
opt(query)
}
cq.withOwner = query
return cq
}
// 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 {
// Card int `json:"card,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Card.Query().
// GroupBy(card.FieldCard).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (cq *CardQuery) GroupBy(field string, fields ...string) *CardGroupBy {
cq.ctx.Fields = append([]string{field}, fields...)
grbuild := &CardGroupBy{build: cq}
grbuild.flds = &cq.ctx.Fields
grbuild.label = card.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 {
// Card int `json:"card,omitempty"`
// }
//
// client.Card.Query().
// Select(card.FieldCard).
// Scan(ctx, &v)
func (cq *CardQuery) Select(fields ...string) *CardSelect {
cq.ctx.Fields = append(cq.ctx.Fields, fields...)
sbuild := &CardSelect{CardQuery: cq}
sbuild.label = card.Label
sbuild.flds, sbuild.scan = &cq.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a CardSelect configured with the given aggregations.
func (cq *CardQuery) Aggregate(fns ...AggregateFunc) *CardSelect {
return cq.Select().Aggregate(fns...)
}
func (cq *CardQuery) prepareQuery(ctx context.Context) error {
for _, inter := range cq.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, cq); err != nil {
return err
}
}
}
for _, f := range cq.ctx.Fields {
if !card.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if cq.path != nil {
prev, err := cq.path(ctx)
if err != nil {
return err
}
cq.sql = prev
}
return nil
}
func (cq *CardQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Card, error) {
var (
nodes = []*Card{}
withFKs = cq.withFKs
_spec = cq.querySpec()
loadedTypes = [1]bool{
cq.withOwner != nil,
}
)
if cq.withOwner != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, card.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Card).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Card{config: cq.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, cq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := cq.withOwner; query != nil {
if err := cq.loadOwner(ctx, query, nodes, nil,
func(n *Card, e *User) { n.Edges.Owner = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (cq *CardQuery) loadOwner(ctx context.Context, query *UserQuery, nodes []*Card, init func(*Card), assign func(*Card, *User)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*Card)
for i := range nodes {
if nodes[i].user_card == nil {
continue
}
fk := *nodes[i].user_card
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(user.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "user_card" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (cq *CardQuery) sqlCount(ctx context.Context) (int, error) {
_spec := cq.querySpec()
_spec.Node.Columns = cq.ctx.Fields
if len(cq.ctx.Fields) > 0 {
_spec.Unique = cq.ctx.Unique != nil && *cq.ctx.Unique
}
return sqlgraph.CountNodes(ctx, cq.driver, _spec)
}
func (cq *CardQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(card.Table, card.Columns, sqlgraph.NewFieldSpec(card.FieldID, field.TypeInt))
_spec.From = cq.sql
if unique := cq.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if cq.path != nil {
_spec.Unique = true
}
if fields := cq.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, card.FieldID)
for i := range fields {
if fields[i] != card.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := cq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := cq.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := cq.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := cq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (cq *CardQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(cq.driver.Dialect())
t1 := builder.Table(card.Table)
columns := cq.ctx.Fields
if len(columns) == 0 {
columns = card.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if cq.sql != nil {
selector = cq.sql
selector.Select(selector.Columns(columns...)...)
}
if cq.ctx.Unique != nil && *cq.ctx.Unique {
selector.Distinct()
}
for _, p := range cq.predicates {
p(selector)
}
for _, p := range cq.order {
p(selector)
}
if offset := cq.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 := cq.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// CardGroupBy is the group-by builder for Card entities.
type CardGroupBy struct {
selector
build *CardQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (cgb *CardGroupBy) Aggregate(fns ...AggregateFunc) *CardGroupBy {
cgb.fns = append(cgb.fns, fns...)
return cgb
}
// Scan applies the selector query and scans the result into the given value.
func (cgb *CardGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, cgb.build.ctx, "GroupBy")
if err := cgb.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*CardQuery, *CardGroupBy](ctx, cgb.build, cgb, cgb.build.inters, v)
}
func (cgb *CardGroupBy) sqlScan(ctx context.Context, root *CardQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(cgb.fns))
for _, fn := range cgb.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*cgb.flds)+len(cgb.fns))
for _, f := range *cgb.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*cgb.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := cgb.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// CardSelect is the builder for selecting fields of Card entities.
type CardSelect struct {
*CardQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (cs *CardSelect) Aggregate(fns ...AggregateFunc) *CardSelect {
cs.fns = append(cs.fns, fns...)
return cs
}
// Scan applies the selector query and scans the result into the given value.
func (cs *CardSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, cs.ctx, "Select")
if err := cs.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*CardQuery, *CardSelect](ctx, cs.CardQuery, cs, cs.inters, v)
}
func (cs *CardSelect) sqlScan(ctx context.Context, root *CardQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(cs.fns))
for _, fn := range cs.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*cs.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 := cs.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

332
ent/card_update.go Normal file
View File

@ -0,0 +1,332 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"t/ent/card"
"t/ent/predicate"
"t/ent/user"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// CardUpdate is the builder for updating Card entities.
type CardUpdate struct {
config
hooks []Hook
mutation *CardMutation
}
// Where appends a list predicates to the CardUpdate builder.
func (cu *CardUpdate) Where(ps ...predicate.Card) *CardUpdate {
cu.mutation.Where(ps...)
return cu
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (cu *CardUpdate) SetOwnerID(id int) *CardUpdate {
cu.mutation.SetOwnerID(id)
return cu
}
// SetOwner sets the "owner" edge to the User entity.
func (cu *CardUpdate) SetOwner(u *User) *CardUpdate {
return cu.SetOwnerID(u.ID)
}
// Mutation returns the CardMutation object of the builder.
func (cu *CardUpdate) Mutation() *CardMutation {
return cu.mutation
}
// ClearOwner clears the "owner" edge to the User entity.
func (cu *CardUpdate) ClearOwner() *CardUpdate {
cu.mutation.ClearOwner()
return cu
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (cu *CardUpdate) Save(ctx context.Context) (int, error) {
return withHooks[int, CardMutation](ctx, cu.sqlSave, cu.mutation, cu.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (cu *CardUpdate) SaveX(ctx context.Context) int {
affected, err := cu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (cu *CardUpdate) Exec(ctx context.Context) error {
_, err := cu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (cu *CardUpdate) ExecX(ctx context.Context) {
if err := cu.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (cu *CardUpdate) check() error {
if _, ok := cu.mutation.OwnerID(); cu.mutation.OwnerCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Card.owner"`)
}
return nil
}
func (cu *CardUpdate) sqlSave(ctx context.Context) (n int, err error) {
if err := cu.check(); err != nil {
return n, err
}
_spec := sqlgraph.NewUpdateSpec(card.Table, card.Columns, sqlgraph.NewFieldSpec(card.FieldID, field.TypeInt))
if ps := cu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if cu.mutation.CardCleared() {
_spec.ClearField(card.FieldCard, field.TypeInt)
}
if cu.mutation.StatusCleared() {
_spec.ClearField(card.FieldStatus, field.TypeString)
}
if cu.mutation.CpCleared() {
_spec.ClearField(card.FieldCp, field.TypeInt)
}
if cu.mutation.URLCleared() {
_spec.ClearField(card.FieldURL, field.TypeString)
}
if cu.mutation.CreatedAtCleared() {
_spec.ClearField(card.FieldCreatedAt, field.TypeTime)
}
if cu.mutation.OwnerCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: card.OwnerTable,
Columns: []string{card.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: user.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := cu.mutation.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: card.OwnerTable,
Columns: []string{card.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: user.FieldID,
},
},
}
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, cu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{card.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
cu.mutation.done = true
return n, nil
}
// CardUpdateOne is the builder for updating a single Card entity.
type CardUpdateOne struct {
config
fields []string
hooks []Hook
mutation *CardMutation
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (cuo *CardUpdateOne) SetOwnerID(id int) *CardUpdateOne {
cuo.mutation.SetOwnerID(id)
return cuo
}
// SetOwner sets the "owner" edge to the User entity.
func (cuo *CardUpdateOne) SetOwner(u *User) *CardUpdateOne {
return cuo.SetOwnerID(u.ID)
}
// Mutation returns the CardMutation object of the builder.
func (cuo *CardUpdateOne) Mutation() *CardMutation {
return cuo.mutation
}
// ClearOwner clears the "owner" edge to the User entity.
func (cuo *CardUpdateOne) ClearOwner() *CardUpdateOne {
cuo.mutation.ClearOwner()
return cuo
}
// Where appends a list predicates to the CardUpdate builder.
func (cuo *CardUpdateOne) Where(ps ...predicate.Card) *CardUpdateOne {
cuo.mutation.Where(ps...)
return cuo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (cuo *CardUpdateOne) Select(field string, fields ...string) *CardUpdateOne {
cuo.fields = append([]string{field}, fields...)
return cuo
}
// Save executes the query and returns the updated Card entity.
func (cuo *CardUpdateOne) Save(ctx context.Context) (*Card, error) {
return withHooks[*Card, CardMutation](ctx, cuo.sqlSave, cuo.mutation, cuo.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (cuo *CardUpdateOne) SaveX(ctx context.Context) *Card {
node, err := cuo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (cuo *CardUpdateOne) Exec(ctx context.Context) error {
_, err := cuo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (cuo *CardUpdateOne) ExecX(ctx context.Context) {
if err := cuo.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (cuo *CardUpdateOne) check() error {
if _, ok := cuo.mutation.OwnerID(); cuo.mutation.OwnerCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Card.owner"`)
}
return nil
}
func (cuo *CardUpdateOne) sqlSave(ctx context.Context) (_node *Card, err error) {
if err := cuo.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(card.Table, card.Columns, sqlgraph.NewFieldSpec(card.FieldID, field.TypeInt))
id, ok := cuo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Card.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := cuo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, card.FieldID)
for _, f := range fields {
if !card.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != card.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := cuo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if cuo.mutation.CardCleared() {
_spec.ClearField(card.FieldCard, field.TypeInt)
}
if cuo.mutation.StatusCleared() {
_spec.ClearField(card.FieldStatus, field.TypeString)
}
if cuo.mutation.CpCleared() {
_spec.ClearField(card.FieldCp, field.TypeInt)
}
if cuo.mutation.URLCleared() {
_spec.ClearField(card.FieldURL, field.TypeString)
}
if cuo.mutation.CreatedAtCleared() {
_spec.ClearField(card.FieldCreatedAt, field.TypeTime)
}
if cuo.mutation.OwnerCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: card.OwnerTable,
Columns: []string{card.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: user.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := cuo.mutation.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: card.OwnerTable,
Columns: []string{card.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: user.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Card{config: cuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, cuo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{card.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
cuo.mutation.done = true
return _node, nil
}

View File

@ -1,18 +1,23 @@
// Code generated by entc, DO NOT EDIT.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"log"
"t/ent/migrate"
"t/ent/users"
"t/ent/card"
"t/ent/group"
"t/ent/user"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
// Client is the client that holds all ent builders.
@ -20,13 +25,17 @@ type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// Users is the client for interacting with the Users builders.
Users *UsersClient
// Card is the client for interacting with the Card builders.
Card *CardClient
// Group is the client for interacting with the Group builders.
Group *GroupClient
// User is the client for interacting with the User builders.
User *UserClient
}
// NewClient creates a new client configured with the given options.
func NewClient(opts ...Option) *Client {
cfg := config{log: log.Println, hooks: &hooks{}}
cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}}
cfg.options(opts...)
client := &Client{config: cfg}
client.init()
@ -35,7 +44,58 @@ func NewClient(opts ...Option) *Client {
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.Users = NewUsersClient(c.config)
c.Card = NewCardClient(c.config)
c.Group = NewGroupClient(c.config)
c.User = NewUserClient(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)
)
// 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
@ -58,7 +118,7 @@ func Open(driverName, dataSourceName string, options ...Option) (*Client, error)
// 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, fmt.Errorf("ent: cannot start a transaction within a transaction")
return nil, errors.New("ent: cannot start a transaction within a transaction")
}
tx, err := newTx(ctx, c.driver)
if err != nil {
@ -69,14 +129,16 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
return &Tx{
ctx: ctx,
config: cfg,
Users: NewUsersClient(cfg),
Card: NewCardClient(cfg),
Group: NewGroupClient(cfg),
User: NewUserClient(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, fmt.Errorf("ent: cannot start a transaction within a transaction")
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)
@ -89,17 +151,18 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
return &Tx{
ctx: ctx,
config: cfg,
Users: NewUsersClient(cfg),
Card: NewCardClient(cfg),
Group: NewGroupClient(cfg),
User: NewUserClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Users.
// Card.
// Query().
// Count(ctx)
//
func (c *Client) Debug() *Client {
if c.debug {
return c
@ -119,87 +182,119 @@ func (c *Client) Close() error {
// Use adds the mutation hooks to all the entity clients.
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) {
c.Users.Use(hooks...)
c.Card.Use(hooks...)
c.Group.Use(hooks...)
c.User.Use(hooks...)
}
// UsersClient is a client for the Users schema.
type UsersClient struct {
config
// 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.Card.Intercept(interceptors...)
c.Group.Intercept(interceptors...)
c.User.Intercept(interceptors...)
}
// NewUsersClient returns a client for the Users from the given config.
func NewUsersClient(c config) *UsersClient {
return &UsersClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `users.Hooks(f(g(h())))`.
func (c *UsersClient) Use(hooks ...Hook) {
c.hooks.Users = append(c.hooks.Users, hooks...)
}
// Create returns a create builder for Users.
func (c *UsersClient) Create() *UsersCreate {
mutation := newUsersMutation(c.config, OpCreate)
return &UsersCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Users entities.
func (c *UsersClient) CreateBulk(builders ...*UsersCreate) *UsersCreateBulk {
return &UsersCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Users.
func (c *UsersClient) Update() *UsersUpdate {
mutation := newUsersMutation(c.config, OpUpdate)
return &UsersUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *UsersClient) UpdateOne(u *Users) *UsersUpdateOne {
mutation := newUsersMutation(c.config, OpUpdateOne, withUsers(u))
return &UsersUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *UsersClient) UpdateOneID(id int) *UsersUpdateOne {
mutation := newUsersMutation(c.config, OpUpdateOne, withUsersID(id))
return &UsersUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Users.
func (c *UsersClient) Delete() *UsersDelete {
mutation := newUsersMutation(c.config, OpDelete)
return &UsersDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a delete builder for the given entity.
func (c *UsersClient) DeleteOne(u *Users) *UsersDeleteOne {
return c.DeleteOneID(u.ID)
}
// DeleteOneID returns a delete builder for the given id.
func (c *UsersClient) DeleteOneID(id int) *UsersDeleteOne {
builder := c.Delete().Where(users.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &UsersDeleteOne{builder}
}
// Query returns a query builder for Users.
func (c *UsersClient) Query() *UsersQuery {
return &UsersQuery{
config: c.config,
// Mutate implements the ent.Mutator interface.
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *CardMutation:
return c.Card.mutate(ctx, m)
case *GroupMutation:
return c.Group.mutate(ctx, m)
case *UserMutation:
return c.User.mutate(ctx, m)
default:
return nil, fmt.Errorf("ent: unknown mutation type %T", m)
}
}
// Get returns a Users entity by its id.
func (c *UsersClient) Get(ctx context.Context, id int) (*Users, error) {
return c.Query().Where(users.ID(id)).Only(ctx)
// CardClient is a client for the Card schema.
type CardClient struct {
config
}
// NewCardClient returns a client for the Card from the given config.
func NewCardClient(c config) *CardClient {
return &CardClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `card.Hooks(f(g(h())))`.
func (c *CardClient) Use(hooks ...Hook) {
c.hooks.Card = append(c.hooks.Card, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `card.Intercept(f(g(h())))`.
func (c *CardClient) Intercept(interceptors ...Interceptor) {
c.inters.Card = append(c.inters.Card, interceptors...)
}
// Create returns a builder for creating a Card entity.
func (c *CardClient) Create() *CardCreate {
mutation := newCardMutation(c.config, OpCreate)
return &CardCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Card entities.
func (c *CardClient) CreateBulk(builders ...*CardCreate) *CardCreateBulk {
return &CardCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Card.
func (c *CardClient) Update() *CardUpdate {
mutation := newCardMutation(c.config, OpUpdate)
return &CardUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *CardClient) UpdateOne(ca *Card) *CardUpdateOne {
mutation := newCardMutation(c.config, OpUpdateOne, withCard(ca))
return &CardUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *CardClient) UpdateOneID(id int) *CardUpdateOne {
mutation := newCardMutation(c.config, OpUpdateOne, withCardID(id))
return &CardUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Card.
func (c *CardClient) Delete() *CardDelete {
mutation := newCardMutation(c.config, OpDelete)
return &CardDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *CardClient) DeleteOne(ca *Card) *CardDeleteOne {
return c.DeleteOneID(ca.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *CardClient) DeleteOneID(id int) *CardDeleteOne {
builder := c.Delete().Where(card.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &CardDeleteOne{builder}
}
// Query returns a query builder for Card.
func (c *CardClient) Query() *CardQuery {
return &CardQuery{
config: c.config,
ctx: &QueryContext{Type: TypeCard},
inters: c.Interceptors(),
}
}
// Get returns a Card entity by its id.
func (c *CardClient) Get(ctx context.Context, id int) (*Card, error) {
return c.Query().Where(card.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *UsersClient) GetX(ctx context.Context, id int) *Users {
func (c *CardClient) GetX(ctx context.Context, id int) *Card {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
@ -207,7 +302,321 @@ func (c *UsersClient) GetX(ctx context.Context, id int) *Users {
return obj
}
// Hooks returns the client hooks.
func (c *UsersClient) Hooks() []Hook {
return c.hooks.Users
// QueryOwner queries the owner edge of a Card.
func (c *CardClient) QueryOwner(ca *Card) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := ca.ID
step := sqlgraph.NewStep(
sqlgraph.From(card.Table, card.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, card.OwnerTable, card.OwnerColumn),
)
fromV = sqlgraph.Neighbors(ca.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *CardClient) Hooks() []Hook {
return c.hooks.Card
}
// Interceptors returns the client interceptors.
func (c *CardClient) Interceptors() []Interceptor {
return c.inters.Card
}
func (c *CardClient) mutate(ctx context.Context, m *CardMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&CardCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&CardUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&CardUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&CardDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Card mutation op: %q", m.Op())
}
}
// GroupClient is a client for the Group schema.
type GroupClient struct {
config
}
// NewGroupClient returns a client for the Group from the given config.
func NewGroupClient(c config) *GroupClient {
return &GroupClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `group.Hooks(f(g(h())))`.
func (c *GroupClient) Use(hooks ...Hook) {
c.hooks.Group = append(c.hooks.Group, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `group.Intercept(f(g(h())))`.
func (c *GroupClient) Intercept(interceptors ...Interceptor) {
c.inters.Group = append(c.inters.Group, interceptors...)
}
// Create returns a builder for creating a Group entity.
func (c *GroupClient) Create() *GroupCreate {
mutation := newGroupMutation(c.config, OpCreate)
return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Group entities.
func (c *GroupClient) CreateBulk(builders ...*GroupCreate) *GroupCreateBulk {
return &GroupCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Group.
func (c *GroupClient) Update() *GroupUpdate {
mutation := newGroupMutation(c.config, OpUpdate)
return &GroupUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *GroupClient) UpdateOne(gr *Group) *GroupUpdateOne {
mutation := newGroupMutation(c.config, OpUpdateOne, withGroup(gr))
return &GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *GroupClient) UpdateOneID(id int) *GroupUpdateOne {
mutation := newGroupMutation(c.config, OpUpdateOne, withGroupID(id))
return &GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Group.
func (c *GroupClient) Delete() *GroupDelete {
mutation := newGroupMutation(c.config, OpDelete)
return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *GroupClient) DeleteOne(gr *Group) *GroupDeleteOne {
return c.DeleteOneID(gr.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne {
builder := c.Delete().Where(group.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &GroupDeleteOne{builder}
}
// Query returns a query builder for Group.
func (c *GroupClient) Query() *GroupQuery {
return &GroupQuery{
config: c.config,
ctx: &QueryContext{Type: TypeGroup},
inters: c.Interceptors(),
}
}
// Get returns a Group entity by its id.
func (c *GroupClient) Get(ctx context.Context, id int) (*Group, error) {
return c.Query().Where(group.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *GroupClient) GetX(ctx context.Context, id int) *Group {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryUsers queries the users edge of a Group.
func (c *GroupClient) QueryUsers(gr *Group) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := gr.ID
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.UsersTable, group.UsersColumn),
)
fromV = sqlgraph.Neighbors(gr.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *GroupClient) Hooks() []Hook {
return c.hooks.Group
}
// Interceptors returns the client interceptors.
func (c *GroupClient) Interceptors() []Interceptor {
return c.inters.Group
}
func (c *GroupClient) mutate(ctx context.Context, m *GroupMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&GroupCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&GroupUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&GroupDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Group mutation op: %q", m.Op())
}
}
// UserClient is a client for the User schema.
type UserClient struct {
config
}
// NewUserClient returns a client for the User from the given config.
func NewUserClient(c config) *UserClient {
return &UserClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `user.Hooks(f(g(h())))`.
func (c *UserClient) Use(hooks ...Hook) {
c.hooks.User = append(c.hooks.User, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `user.Intercept(f(g(h())))`.
func (c *UserClient) Intercept(interceptors ...Interceptor) {
c.inters.User = append(c.inters.User, interceptors...)
}
// Create returns a builder for creating a User entity.
func (c *UserClient) Create() *UserCreate {
mutation := newUserMutation(c.config, OpCreate)
return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of User entities.
func (c *UserClient) CreateBulk(builders ...*UserCreate) *UserCreateBulk {
return &UserCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for User.
func (c *UserClient) Update() *UserUpdate {
mutation := newUserMutation(c.config, OpUpdate)
return &UserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *UserClient) UpdateOne(u *User) *UserUpdateOne {
mutation := newUserMutation(c.config, OpUpdateOne, withUser(u))
return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *UserClient) UpdateOneID(id int) *UserUpdateOne {
mutation := newUserMutation(c.config, OpUpdateOne, withUserID(id))
return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for User.
func (c *UserClient) Delete() *UserDelete {
mutation := newUserMutation(c.config, OpDelete)
return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *UserClient) DeleteOne(u *User) *UserDeleteOne {
return c.DeleteOneID(u.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *UserClient) DeleteOneID(id int) *UserDeleteOne {
builder := c.Delete().Where(user.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &UserDeleteOne{builder}
}
// Query returns a query builder for User.
func (c *UserClient) Query() *UserQuery {
return &UserQuery{
config: c.config,
ctx: &QueryContext{Type: TypeUser},
inters: c.Interceptors(),
}
}
// Get returns a User entity by its id.
func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {
return c.Query().Where(user.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *UserClient) GetX(ctx context.Context, id int) *User {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryCard queries the card edge of a User.
func (c *UserClient) QueryCard(u *User) *CardQuery {
query := (&CardClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := u.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(card.Table, card.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, user.CardTable, user.CardColumn),
)
fromV = sqlgraph.Neighbors(u.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *UserClient) Hooks() []Hook {
return c.hooks.User
}
// Interceptors returns the client interceptors.
func (c *UserClient) Interceptors() []Interceptor {
return c.inters.User
}
func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&UserCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&UserUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&UserDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown User mutation op: %q", m.Op())
}
}
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Card, Group, User []ent.Hook
}
inters struct {
Card, Group, User []ent.Interceptor
}
)

View File

@ -1,59 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"entgo.io/ent"
"entgo.io/ent/dialect"
)
// Option function to configure the client.
type Option func(*config)
// Config is the configuration for the client and its builder.
type 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(...interface{})
// hooks to execute on mutations.
hooks *hooks
}
// hooks per client, for fast access.
type hooks struct {
Users []ent.Hook
}
// 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(...interface{})) 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
}
}

View File

@ -1,33 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
)
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)
}

View File

@ -1,14 +1,19 @@
// Code generated by entc, DO NOT EDIT.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"t/ent/users"
"reflect"
"t/ent/card"
"t/ent/group"
"t/ent/user"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
// ent aliases to avoid import conflicts in user's code.
@ -17,19 +22,54 @@ type (
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.
type OrderFunc func(*sql.Selector)
// columnChecker returns a function indicates if the column exists in the given column.
func columnChecker(table string) func(string) error {
checks := map[string]func(string) bool{
users.Table: users.ValidColumn,
card.Table: card.ValidColumn,
group.Table: group.ValidColumn,
user.Table: user.ValidColumn,
}
check, ok := checks[table]
if !ok {
@ -79,7 +119,6 @@ type AggregateFunc func(*sql.Selector) string
// 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)
@ -257,3 +296,325 @@ func IsConstraintError(err error) bool {
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 := 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)

View File

@ -5,13 +5,14 @@ package main
import (
"log"
"ariga.io/ogent"
"entgo.io/contrib/entoas"
"entgo.io/ent/entc"
"entgo.io/ent/entc/gen"
"github.com/ariga/ogent"
"github.com/ogen-go/ogen"
)
func main() {
spec := new(ogen.Spec)
@ -19,12 +20,12 @@ func main() {
oas, err := entoas.NewExtension(
entoas.Spec(spec),
entoas.Mutations(func(_ *gen.Graph, spec *ogen.Spec) error {
spec.AddPathItem("/users/{id}/start", ogen.NewPathItem().
spec.AddPathItem("/users/{id}/card/start", ogen.NewPathItem().
SetDescription("Start an draw as done").
SetPatch(ogen.NewOperation().
SetOperationID("drawStart").
SetSummary("Draws a card item as done.").
AddTags("Users").
AddTags("Card").
AddResponse("204", ogen.NewResponse().SetDescription("Item marked as done")),
).
AddParameters(ogen.NewParameter().
@ -51,12 +52,12 @@ return nil
// return nil
// }),
entoas.Mutations(func(_ *gen.Graph, spec *ogen.Spec) error {
spec.AddPathItem("/users/{id}/d", ogen.NewPathItem().
spec.AddPathItem("/cards/{id}/d", ogen.NewPathItem().
SetDescription("Start an draw as done").
SetPut(ogen.NewOperation().
SetOperationID("drawDone").
SetSummary("Draws a card item as done.").
AddTags("Users").
AddTags("Card").
AddResponse("204", ogen.NewResponse().SetDescription("Item marked as done")),
//AddResponse("204", ogen.NewResponse().SetDescription("Item marked as done").SetSchema("test")),
).

View File

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT.
// Code generated by ent, DO NOT EDIT.
package enttest
@ -8,6 +8,8 @@ import (
// required by schema hooks.
_ "t/ent/runtime"
"t/ent/migrate"
"entgo.io/ent/dialect/sql/schema"
)
@ -16,7 +18,7 @@ type (
// testing.T and testing.B and used by enttest.
TestingT interface {
FailNow()
Error(...interface{})
Error(...any)
}
// Option configures client creation.
@ -58,10 +60,7 @@ func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Cl
t.Error(err)
t.FailNow()
}
if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil {
t.Error(err)
t.FailNow()
}
migrateSchema(t, c, o)
return c
}
@ -69,9 +68,17 @@ func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Cl
func NewClient(t TestingT, opts ...Option) *ent.Client {
o := newOptions(opts)
c := ent.NewClient(o.opts...)
if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil {
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()
}
return c
}

View File

@ -1,4 +1,3 @@
package ent
//go:generate go run -mod=mod entc.go

119
ent/group.go Normal file
View File

@ -0,0 +1,119 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"t/ent/group"
"entgo.io/ent/dialect/sql"
)
// Group is the model entity for the Group schema.
type Group struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the GroupQuery when eager-loading is set.
Edges GroupEdges `json:"edges"`
}
// GroupEdges holds the relations/edges for other nodes in the graph.
type GroupEdges struct {
// Users holds the value of the users edge.
Users []*User `json:"users,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// UsersOrErr returns the Users value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) UsersOrErr() ([]*User, error) {
if e.loadedTypes[0] {
return e.Users, nil
}
return nil, &NotLoadedError{edge: "users"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Group) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case group.FieldID:
values[i] = new(sql.NullInt64)
case group.FieldName:
values[i] = new(sql.NullString)
default:
return nil, fmt.Errorf("unexpected column %q for type Group", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Group fields.
func (gr *Group) 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 group.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
gr.ID = int(value.Int64)
case group.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
gr.Name = value.String
}
}
}
return nil
}
// QueryUsers queries the "users" edge of the Group entity.
func (gr *Group) QueryUsers() *UserQuery {
return NewGroupClient(gr.config).QueryUsers(gr)
}
// Update returns a builder for updating this Group.
// Note that you need to call Group.Unwrap() before calling this method if this Group
// was returned from a transaction, and the transaction was committed or rolled back.
func (gr *Group) Update() *GroupUpdateOne {
return NewGroupClient(gr.config).UpdateOne(gr)
}
// Unwrap unwraps the Group 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 (gr *Group) Unwrap() *Group {
_tx, ok := gr.config.driver.(*txDriver)
if !ok {
panic("ent: Group is not a transactional entity")
}
gr.config.driver = _tx.drv
return gr
}
// String implements the fmt.Stringer.
func (gr *Group) String() string {
var builder strings.Builder
builder.WriteString("Group(")
builder.WriteString(fmt.Sprintf("id=%v, ", gr.ID))
builder.WriteString("name=")
builder.WriteString(gr.Name)
builder.WriteByte(')')
return builder.String()
}
// Groups is a parsable slice of Group.
type Groups []*Group

39
ent/group/group.go Normal file
View File

@ -0,0 +1,39 @@
// Code generated by ent, DO NOT EDIT.
package group
const (
// Label holds the string label denoting the group type in the database.
Label = "group"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// EdgeUsers holds the string denoting the users edge name in mutations.
EdgeUsers = "users"
// Table holds the table name of the group in the database.
Table = "groups"
// UsersTable is the table that holds the users relation/edge.
UsersTable = "users"
// UsersInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
UsersInverseTable = "users"
// UsersColumn is the table column denoting the users relation/edge.
UsersColumn = "group_users"
)
// Columns holds all SQL columns for group fields.
var Columns = []string{
FieldID,
FieldName,
}
// 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
}

184
ent/group/where.go Normal file
View File

@ -0,0 +1,184 @@
// Code generated by ent, DO NOT EDIT.
package group
import (
"t/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Group {
return predicate.Group(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Group {
return predicate.Group(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Group {
return predicate.Group(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldID, id))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldName, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Group {
return predicate.Group(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Group {
return predicate.Group(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Group {
return predicate.Group(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Group {
return predicate.Group(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Group {
return predicate.Group(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Group {
return predicate.Group(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Group {
return predicate.Group(sql.FieldContainsFold(FieldName, v))
}
// HasUsers applies the HasEdge predicate on the "users" edge.
func HasUsers() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, UsersTable, UsersColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasUsersWith applies the HasEdge predicate on the "users" edge with a given conditions (other predicates).
func HasUsersWith(preds ...predicate.User) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UsersInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, UsersTable, UsersColumn),
)
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.Group) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Group) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Group) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
p(s.Not())
})
}

214
ent/group_create.go Normal file
View File

@ -0,0 +1,214 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"t/ent/group"
"t/ent/user"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// GroupCreate is the builder for creating a Group entity.
type GroupCreate struct {
config
mutation *GroupMutation
hooks []Hook
}
// SetName sets the "name" field.
func (gc *GroupCreate) SetName(s string) *GroupCreate {
gc.mutation.SetName(s)
return gc
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (gc *GroupCreate) AddUserIDs(ids ...int) *GroupCreate {
gc.mutation.AddUserIDs(ids...)
return gc
}
// AddUsers adds the "users" edges to the User entity.
func (gc *GroupCreate) AddUsers(u ...*User) *GroupCreate {
ids := make([]int, len(u))
for i := range u {
ids[i] = u[i].ID
}
return gc.AddUserIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder.
func (gc *GroupCreate) Mutation() *GroupMutation {
return gc.mutation
}
// Save creates the Group in the database.
func (gc *GroupCreate) Save(ctx context.Context) (*Group, error) {
return withHooks[*Group, GroupMutation](ctx, gc.sqlSave, gc.mutation, gc.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (gc *GroupCreate) SaveX(ctx context.Context) *Group {
v, err := gc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (gc *GroupCreate) Exec(ctx context.Context) error {
_, err := gc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (gc *GroupCreate) ExecX(ctx context.Context) {
if err := gc.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (gc *GroupCreate) check() error {
if _, ok := gc.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Group.name"`)}
}
return nil
}
func (gc *GroupCreate) sqlSave(ctx context.Context) (*Group, error) {
if err := gc.check(); err != nil {
return nil, err
}
_node, _spec := gc.createSpec()
if err := sqlgraph.CreateNode(ctx, gc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
gc.mutation.id = &_node.ID
gc.mutation.done = true
return _node, nil
}
func (gc *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
var (
_node = &Group{config: gc.config}
_spec = sqlgraph.NewCreateSpec(group.Table, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt))
)
if value, ok := gc.mutation.Name(); ok {
_spec.SetField(group.FieldName, field.TypeString, value)
_node.Name = value
}
if nodes := gc.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.UsersTable,
Columns: []string{group.UsersColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: user.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// GroupCreateBulk is the builder for creating many Group entities in bulk.
type GroupCreateBulk struct {
config
builders []*GroupCreate
}
// Save creates the Group entities in the database.
func (gcb *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) {
specs := make([]*sqlgraph.CreateSpec, len(gcb.builders))
nodes := make([]*Group, len(gcb.builders))
mutators := make([]Mutator, len(gcb.builders))
for i := range gcb.builders {
func(i int, root context.Context) {
builder := gcb.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GroupMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, gcb.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, gcb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, gcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (gcb *GroupCreateBulk) SaveX(ctx context.Context) []*Group {
v, err := gcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (gcb *GroupCreateBulk) Exec(ctx context.Context) error {
_, err := gcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (gcb *GroupCreateBulk) ExecX(ctx context.Context) {
if err := gcb.Exec(ctx); err != nil {
panic(err)
}
}

88
ent/group_delete.go Normal file
View File

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

606
ent/group_query.go Normal file
View File

@ -0,0 +1,606 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"fmt"
"math"
"t/ent/group"
"t/ent/predicate"
"t/ent/user"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// GroupQuery is the builder for querying Group entities.
type GroupQuery struct {
config
ctx *QueryContext
order []OrderFunc
inters []Interceptor
predicates []predicate.Group
withUsers *UserQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the GroupQuery builder.
func (gq *GroupQuery) Where(ps ...predicate.Group) *GroupQuery {
gq.predicates = append(gq.predicates, ps...)
return gq
}
// Limit the number of records to be returned by this query.
func (gq *GroupQuery) Limit(limit int) *GroupQuery {
gq.ctx.Limit = &limit
return gq
}
// Offset to start from.
func (gq *GroupQuery) Offset(offset int) *GroupQuery {
gq.ctx.Offset = &offset
return gq
}
// 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 (gq *GroupQuery) Unique(unique bool) *GroupQuery {
gq.ctx.Unique = &unique
return gq
}
// Order specifies how the records should be ordered.
func (gq *GroupQuery) Order(o ...OrderFunc) *GroupQuery {
gq.order = append(gq.order, o...)
return gq
}
// QueryUsers chains the current query on the "users" edge.
func (gq *GroupQuery) QueryUsers() *UserQuery {
query := (&UserClient{config: gq.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := gq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.UsersTable, group.UsersColumn),
)
fromU = sqlgraph.SetNeighbors(gq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Group entity from the query.
// Returns a *NotFoundError when no Group was found.
func (gq *GroupQuery) First(ctx context.Context) (*Group, error) {
nodes, err := gq.Limit(1).All(setContextOp(ctx, gq.ctx, "First"))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{group.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (gq *GroupQuery) FirstX(ctx context.Context) *Group {
node, err := gq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Group ID from the query.
// Returns a *NotFoundError when no Group ID was found.
func (gq *GroupQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = gq.Limit(1).IDs(setContextOp(ctx, gq.ctx, "FirstID")); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{group.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (gq *GroupQuery) FirstIDX(ctx context.Context) int {
id, err := gq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Group entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Group entity is found.
// Returns a *NotFoundError when no Group entities are found.
func (gq *GroupQuery) Only(ctx context.Context) (*Group, error) {
nodes, err := gq.Limit(2).All(setContextOp(ctx, gq.ctx, "Only"))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{group.Label}
default:
return nil, &NotSingularError{group.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (gq *GroupQuery) OnlyX(ctx context.Context) *Group {
node, err := gq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Group ID in the query.
// Returns a *NotSingularError when more than one Group ID is found.
// Returns a *NotFoundError when no entities are found.
func (gq *GroupQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = gq.Limit(2).IDs(setContextOp(ctx, gq.ctx, "OnlyID")); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{group.Label}
default:
err = &NotSingularError{group.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (gq *GroupQuery) OnlyIDX(ctx context.Context) int {
id, err := gq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Groups.
func (gq *GroupQuery) All(ctx context.Context) ([]*Group, error) {
ctx = setContextOp(ctx, gq.ctx, "All")
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Group, *GroupQuery]()
return withInterceptors[[]*Group](ctx, gq, qr, gq.inters)
}
// AllX is like All, but panics if an error occurs.
func (gq *GroupQuery) AllX(ctx context.Context) []*Group {
nodes, err := gq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Group IDs.
func (gq *GroupQuery) IDs(ctx context.Context) (ids []int, err error) {
if gq.ctx.Unique == nil && gq.path != nil {
gq.Unique(true)
}
ctx = setContextOp(ctx, gq.ctx, "IDs")
if err = gq.Select(group.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (gq *GroupQuery) IDsX(ctx context.Context) []int {
ids, err := gq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (gq *GroupQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, gq.ctx, "Count")
if err := gq.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, gq, querierCount[*GroupQuery](), gq.inters)
}
// CountX is like Count, but panics if an error occurs.
func (gq *GroupQuery) CountX(ctx context.Context) int {
count, err := gq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (gq *GroupQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, gq.ctx, "Exist")
switch _, err := gq.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 (gq *GroupQuery) ExistX(ctx context.Context) bool {
exist, err := gq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the GroupQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (gq *GroupQuery) Clone() *GroupQuery {
if gq == nil {
return nil
}
return &GroupQuery{
config: gq.config,
ctx: gq.ctx.Clone(),
order: append([]OrderFunc{}, gq.order...),
inters: append([]Interceptor{}, gq.inters...),
predicates: append([]predicate.Group{}, gq.predicates...),
withUsers: gq.withUsers.Clone(),
// clone intermediate query.
sql: gq.sql.Clone(),
path: gq.path,
}
}
// WithUsers tells the query-builder to eager-load the nodes that are connected to
// the "users" edge. The optional arguments are used to configure the query builder of the edge.
func (gq *GroupQuery) WithUsers(opts ...func(*UserQuery)) *GroupQuery {
query := (&UserClient{config: gq.config}).Query()
for _, opt := range opts {
opt(query)
}
gq.withUsers = query
return gq
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Name string `json:"name,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Group.Query().
// GroupBy(group.FieldName).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (gq *GroupQuery) GroupBy(field string, fields ...string) *GroupGroupBy {
gq.ctx.Fields = append([]string{field}, fields...)
grbuild := &GroupGroupBy{build: gq}
grbuild.flds = &gq.ctx.Fields
grbuild.label = group.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// Name string `json:"name,omitempty"`
// }
//
// client.Group.Query().
// Select(group.FieldName).
// Scan(ctx, &v)
func (gq *GroupQuery) Select(fields ...string) *GroupSelect {
gq.ctx.Fields = append(gq.ctx.Fields, fields...)
sbuild := &GroupSelect{GroupQuery: gq}
sbuild.label = group.Label
sbuild.flds, sbuild.scan = &gq.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a GroupSelect configured with the given aggregations.
func (gq *GroupQuery) Aggregate(fns ...AggregateFunc) *GroupSelect {
return gq.Select().Aggregate(fns...)
}
func (gq *GroupQuery) prepareQuery(ctx context.Context) error {
for _, inter := range gq.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, gq); err != nil {
return err
}
}
}
for _, f := range gq.ctx.Fields {
if !group.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if gq.path != nil {
prev, err := gq.path(ctx)
if err != nil {
return err
}
gq.sql = prev
}
return nil
}
func (gq *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group, error) {
var (
nodes = []*Group{}
_spec = gq.querySpec()
loadedTypes = [1]bool{
gq.withUsers != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Group).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Group{config: gq.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, gq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := gq.withUsers; query != nil {
if err := gq.loadUsers(ctx, query, nodes,
func(n *Group) { n.Edges.Users = []*User{} },
func(n *Group, e *User) { n.Edges.Users = append(n.Edges.Users, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (gq *GroupQuery) loadUsers(ctx context.Context, query *UserQuery, nodes []*Group, init func(*Group), assign func(*Group, *User)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[int]*Group)
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.User(func(s *sql.Selector) {
s.Where(sql.InValues(group.UsersColumn, fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.group_users
if fk == nil {
return fmt.Errorf(`foreign-key "group_users" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_users" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (gq *GroupQuery) sqlCount(ctx context.Context) (int, error) {
_spec := gq.querySpec()
_spec.Node.Columns = gq.ctx.Fields
if len(gq.ctx.Fields) > 0 {
_spec.Unique = gq.ctx.Unique != nil && *gq.ctx.Unique
}
return sqlgraph.CountNodes(ctx, gq.driver, _spec)
}
func (gq *GroupQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt))
_spec.From = gq.sql
if unique := gq.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if gq.path != nil {
_spec.Unique = true
}
if fields := gq.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, group.FieldID)
for i := range fields {
if fields[i] != group.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := gq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := gq.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := gq.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := gq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (gq *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(gq.driver.Dialect())
t1 := builder.Table(group.Table)
columns := gq.ctx.Fields
if len(columns) == 0 {
columns = group.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if gq.sql != nil {
selector = gq.sql
selector.Select(selector.Columns(columns...)...)
}
if gq.ctx.Unique != nil && *gq.ctx.Unique {
selector.Distinct()
}
for _, p := range gq.predicates {
p(selector)
}
for _, p := range gq.order {
p(selector)
}
if offset := gq.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 := gq.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// GroupGroupBy is the group-by builder for Group entities.
type GroupGroupBy struct {
selector
build *GroupQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (ggb *GroupGroupBy) Aggregate(fns ...AggregateFunc) *GroupGroupBy {
ggb.fns = append(ggb.fns, fns...)
return ggb
}
// Scan applies the selector query and scans the result into the given value.
func (ggb *GroupGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, ggb.build.ctx, "GroupBy")
if err := ggb.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*GroupQuery, *GroupGroupBy](ctx, ggb.build, ggb, ggb.build.inters, v)
}
func (ggb *GroupGroupBy) sqlScan(ctx context.Context, root *GroupQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(ggb.fns))
for _, fn := range ggb.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*ggb.flds)+len(ggb.fns))
for _, f := range *ggb.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*ggb.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := ggb.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// GroupSelect is the builder for selecting fields of Group entities.
type GroupSelect struct {
*GroupQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (gs *GroupSelect) Aggregate(fns ...AggregateFunc) *GroupSelect {
gs.fns = append(gs.fns, fns...)
return gs
}
// Scan applies the selector query and scans the result into the given value.
func (gs *GroupSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, gs.ctx, "Select")
if err := gs.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*GroupQuery, *GroupSelect](ctx, gs.GroupQuery, gs, gs.inters, v)
}
func (gs *GroupSelect) sqlScan(ctx context.Context, root *GroupQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(gs.fns))
for _, fn := range gs.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*gs.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 := gs.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

374
ent/group_update.go Normal file
View File

@ -0,0 +1,374 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"t/ent/group"
"t/ent/predicate"
"t/ent/user"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// GroupUpdate is the builder for updating Group entities.
type GroupUpdate struct {
config
hooks []Hook
mutation *GroupMutation
}
// Where appends a list predicates to the GroupUpdate builder.
func (gu *GroupUpdate) Where(ps ...predicate.Group) *GroupUpdate {
gu.mutation.Where(ps...)
return gu
}
// SetName sets the "name" field.
func (gu *GroupUpdate) SetName(s string) *GroupUpdate {
gu.mutation.SetName(s)
return gu
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (gu *GroupUpdate) AddUserIDs(ids ...int) *GroupUpdate {
gu.mutation.AddUserIDs(ids...)
return gu
}
// AddUsers adds the "users" edges to the User entity.
func (gu *GroupUpdate) AddUsers(u ...*User) *GroupUpdate {
ids := make([]int, len(u))
for i := range u {
ids[i] = u[i].ID
}
return gu.AddUserIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder.
func (gu *GroupUpdate) Mutation() *GroupMutation {
return gu.mutation
}
// ClearUsers clears all "users" edges to the User entity.
func (gu *GroupUpdate) ClearUsers() *GroupUpdate {
gu.mutation.ClearUsers()
return gu
}
// RemoveUserIDs removes the "users" edge to User entities by IDs.
func (gu *GroupUpdate) RemoveUserIDs(ids ...int) *GroupUpdate {
gu.mutation.RemoveUserIDs(ids...)
return gu
}
// RemoveUsers removes "users" edges to User entities.
func (gu *GroupUpdate) RemoveUsers(u ...*User) *GroupUpdate {
ids := make([]int, len(u))
for i := range u {
ids[i] = u[i].ID
}
return gu.RemoveUserIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (gu *GroupUpdate) Save(ctx context.Context) (int, error) {
return withHooks[int, GroupMutation](ctx, gu.sqlSave, gu.mutation, gu.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (gu *GroupUpdate) SaveX(ctx context.Context) int {
affected, err := gu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (gu *GroupUpdate) Exec(ctx context.Context) error {
_, err := gu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (gu *GroupUpdate) ExecX(ctx context.Context) {
if err := gu.Exec(ctx); err != nil {
panic(err)
}
}
func (gu *GroupUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := sqlgraph.NewUpdateSpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt))
if ps := gu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := gu.mutation.Name(); ok {
_spec.SetField(group.FieldName, field.TypeString, value)
}
if gu.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.UsersTable,
Columns: []string{group.UsersColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: user.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := gu.mutation.RemovedUsersIDs(); len(nodes) > 0 && !gu.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.UsersTable,
Columns: []string{group.UsersColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: user.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := gu.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.UsersTable,
Columns: []string{group.UsersColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: user.FieldID,
},
},
}
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, gu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{group.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
gu.mutation.done = true
return n, nil
}
// GroupUpdateOne is the builder for updating a single Group entity.
type GroupUpdateOne struct {
config
fields []string
hooks []Hook
mutation *GroupMutation
}
// SetName sets the "name" field.
func (guo *GroupUpdateOne) SetName(s string) *GroupUpdateOne {
guo.mutation.SetName(s)
return guo
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (guo *GroupUpdateOne) AddUserIDs(ids ...int) *GroupUpdateOne {
guo.mutation.AddUserIDs(ids...)
return guo
}
// AddUsers adds the "users" edges to the User entity.
func (guo *GroupUpdateOne) AddUsers(u ...*User) *GroupUpdateOne {
ids := make([]int, len(u))
for i := range u {
ids[i] = u[i].ID
}
return guo.AddUserIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder.
func (guo *GroupUpdateOne) Mutation() *GroupMutation {
return guo.mutation
}
// ClearUsers clears all "users" edges to the User entity.
func (guo *GroupUpdateOne) ClearUsers() *GroupUpdateOne {
guo.mutation.ClearUsers()
return guo
}
// RemoveUserIDs removes the "users" edge to User entities by IDs.
func (guo *GroupUpdateOne) RemoveUserIDs(ids ...int) *GroupUpdateOne {
guo.mutation.RemoveUserIDs(ids...)
return guo
}
// RemoveUsers removes "users" edges to User entities.
func (guo *GroupUpdateOne) RemoveUsers(u ...*User) *GroupUpdateOne {
ids := make([]int, len(u))
for i := range u {
ids[i] = u[i].ID
}
return guo.RemoveUserIDs(ids...)
}
// Where appends a list predicates to the GroupUpdate builder.
func (guo *GroupUpdateOne) Where(ps ...predicate.Group) *GroupUpdateOne {
guo.mutation.Where(ps...)
return guo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (guo *GroupUpdateOne) Select(field string, fields ...string) *GroupUpdateOne {
guo.fields = append([]string{field}, fields...)
return guo
}
// Save executes the query and returns the updated Group entity.
func (guo *GroupUpdateOne) Save(ctx context.Context) (*Group, error) {
return withHooks[*Group, GroupMutation](ctx, guo.sqlSave, guo.mutation, guo.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (guo *GroupUpdateOne) SaveX(ctx context.Context) *Group {
node, err := guo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (guo *GroupUpdateOne) Exec(ctx context.Context) error {
_, err := guo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (guo *GroupUpdateOne) ExecX(ctx context.Context) {
if err := guo.Exec(ctx); err != nil {
panic(err)
}
}
func (guo *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error) {
_spec := sqlgraph.NewUpdateSpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt))
id, ok := guo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Group.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := guo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, group.FieldID)
for _, f := range fields {
if !group.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != group.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := guo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := guo.mutation.Name(); ok {
_spec.SetField(group.FieldName, field.TypeString, value)
}
if guo.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.UsersTable,
Columns: []string{group.UsersColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: user.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := guo.mutation.RemovedUsersIDs(); len(nodes) > 0 && !guo.mutation.UsersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.UsersTable,
Columns: []string{group.UsersColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: user.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := guo.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.UsersTable,
Columns: []string{group.UsersColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: user.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Group{config: guo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, guo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{group.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
guo.mutation.done = true
return _node, nil
}

View File

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT.
// Code generated by ent, DO NOT EDIT.
package hook
@ -8,17 +8,40 @@ import (
"t/ent"
)
// The UsersFunc type is an adapter to allow the use of ordinary
// function as Users mutator.
type UsersFunc func(context.Context, *ent.UsersMutation) (ent.Value, error)
// The CardFunc type is an adapter to allow the use of ordinary
// function as Card mutator.
type CardFunc func(context.Context, *ent.CardMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f UsersFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.UsersMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UsersMutation", m)
}
func (f CardFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.CardMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.CardMutation", m)
}
// The GroupFunc type is an adapter to allow the use of ordinary
// function as Group mutator.
type GroupFunc func(context.Context, *ent.GroupMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f GroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.GroupMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GroupMutation", m)
}
// The UserFunc type is an adapter to allow the use of ordinary
// function as User mutator.
type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.UserMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", m)
}
// Condition is a hook condition function.
@ -116,7 +139,6 @@ func HasFields(field string, fields ...string) Condition {
// 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) {
@ -131,7 +153,6 @@ func If(hk ent.Hook, cond Condition) ent.Hook {
// 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))
}
@ -139,7 +160,6 @@ func On(hk ent.Hook, op ent.Op) ent.Hook {
// 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)))
}
@ -160,7 +180,6 @@ func FixedError(err error) 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)

View File

@ -1,224 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package http
import (
"net/http"
"strings"
"t/ent"
"t/ent/compartment"
"t/ent/entry"
"t/ent/fridge"
"t/ent/item"
"github.com/mailru/easyjson"
"go.uber.org/zap"
)
// Create creates a new ent.Compartment and stores it in the database.
func (h CompartmentHandler) Create(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Create"))
// Get the post data.
var d CompartmentCreateRequest
if err := easyjson.UnmarshalFromReader(r.Body, &d); err != nil {
l.Error("error decoding json", zap.Error(err))
BadRequest(w, "invalid json string")
return
}
// Save the data.
b := h.client.Compartment.Create()
e, err := b.Save(r.Context())
if err != nil {
switch {
default:
l.Error("could not create compartment", zap.Error(err))
InternalServerError(w, nil)
}
return
}
// Store id of fresh entity to log errors for the reload.
id := e.ID
// Reload entry.
q := h.client.Compartment.Query().Where(compartment.ID(e.ID))
ret, err := q.Only(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.Int("id", id))
NotFound(w, msg)
case ent.IsNotSingular(err):
msg := stripEntError(err)
l.Error(msg, zap.Error(err), zap.Int("id", id))
BadRequest(w, msg)
default:
l.Error("could not read compartment", zap.Error(err), zap.Int("id", id))
InternalServerError(w, nil)
}
return
}
l.Info("compartment rendered", zap.Int("id", id))
easyjson.MarshalToHTTPResponseWriter(NewCompartment3324871446View(ret), w)
}
// Create creates a new ent.Entry and stores it in the database.
func (h EntryHandler) Create(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Create"))
// Get the post data.
var d EntryCreateRequest
if err := easyjson.UnmarshalFromReader(r.Body, &d); err != nil {
l.Error("error decoding json", zap.Error(err))
BadRequest(w, "invalid json string")
return
}
// Validate the data.
errs := make(map[string]string)
if d.User == nil {
errs["user"] = `missing required field: "user"`
} else if err := entry.UserValidator(*d.User); err != nil {
errs["user"] = strings.TrimPrefix(err.Error(), "entry: ")
}
if d.First == nil {
errs["first"] = `missing required field: "first"`
}
if len(errs) > 0 {
l.Info("validation failed", zapFields(errs)...)
BadRequest(w, errs)
return
}
// Save the data.
b := h.client.Entry.Create()
if d.User != nil {
b.SetUser(*d.User)
}
if d.First != nil {
b.SetFirst(*d.First)
}
if d.CreatedAt != nil {
b.SetCreatedAt(*d.CreatedAt)
}
e, err := b.Save(r.Context())
if err != nil {
switch {
default:
l.Error("could not create entry", zap.Error(err))
InternalServerError(w, nil)
}
return
}
// Store id of fresh entity to log errors for the reload.
id := e.ID
// Reload entry.
q := h.client.Entry.Query().Where(entry.ID(e.ID))
ret, err := q.Only(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.String("id", id))
NotFound(w, msg)
case ent.IsNotSingular(err):
msg := stripEntError(err)
l.Error(msg, zap.Error(err), zap.String("id", id))
BadRequest(w, msg)
default:
l.Error("could not read entry", zap.Error(err), zap.String("id", id))
InternalServerError(w, nil)
}
return
}
l.Info("entry rendered", zap.String("id", id))
easyjson.MarshalToHTTPResponseWriter(NewEntry2675665849View(ret), w)
}
// Create creates a new ent.Fridge and stores it in the database.
func (h FridgeHandler) Create(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Create"))
// Get the post data.
var d FridgeCreateRequest
if err := easyjson.UnmarshalFromReader(r.Body, &d); err != nil {
l.Error("error decoding json", zap.Error(err))
BadRequest(w, "invalid json string")
return
}
// Save the data.
b := h.client.Fridge.Create()
e, err := b.Save(r.Context())
if err != nil {
switch {
default:
l.Error("could not create fridge", zap.Error(err))
InternalServerError(w, nil)
}
return
}
// Store id of fresh entity to log errors for the reload.
id := e.ID
// Reload entry.
q := h.client.Fridge.Query().Where(fridge.ID(e.ID))
ret, err := q.Only(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.Int("id", id))
NotFound(w, msg)
case ent.IsNotSingular(err):
msg := stripEntError(err)
l.Error(msg, zap.Error(err), zap.Int("id", id))
BadRequest(w, msg)
default:
l.Error("could not read fridge", zap.Error(err), zap.Int("id", id))
InternalServerError(w, nil)
}
return
}
l.Info("fridge rendered", zap.Int("id", id))
easyjson.MarshalToHTTPResponseWriter(NewFridge2211356377View(ret), w)
}
// Create creates a new ent.Item and stores it in the database.
func (h ItemHandler) Create(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Create"))
// Get the post data.
var d ItemCreateRequest
if err := easyjson.UnmarshalFromReader(r.Body, &d); err != nil {
l.Error("error decoding json", zap.Error(err))
BadRequest(w, "invalid json string")
return
}
// Save the data.
b := h.client.Item.Create()
e, err := b.Save(r.Context())
if err != nil {
switch {
default:
l.Error("could not create item", zap.Error(err))
InternalServerError(w, nil)
}
return
}
// Store id of fresh entity to log errors for the reload.
id := e.ID
// Reload entry.
q := h.client.Item.Query().Where(item.ID(e.ID))
ret, err := q.Only(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.Int("id", id))
NotFound(w, msg)
case ent.IsNotSingular(err):
msg := stripEntError(err)
l.Error(msg, zap.Error(err), zap.Int("id", id))
BadRequest(w, msg)
default:
l.Error("could not read item", zap.Error(err), zap.Int("id", id))
InternalServerError(w, nil)
}
return
}
l.Info("item rendered", zap.Int("id", id))
easyjson.MarshalToHTTPResponseWriter(NewItem1548468123View(ret), w)
}

View File

@ -1,116 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package http
import (
"net/http"
"strconv"
"t/ent"
"github.com/go-chi/chi/v5"
"go.uber.org/zap"
)
// Delete removes a ent.Compartment from the database.
func (h CompartmentHandler) Delete(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Delete"))
// ID is URL parameter.
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
BadRequest(w, "id must be an integer")
return
}
err = h.client.Compartment.DeleteOneID(id).Exec(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.Int("id", id))
NotFound(w, msg)
default:
l.Error("could-not-delete-compartment", zap.Error(err), zap.Int("id", id))
InternalServerError(w, nil)
}
return
}
l.Info("compartment deleted", zap.Int("id", id))
w.WriteHeader(http.StatusNoContent)
}
// Delete removes a ent.Entry from the database.
func (h EntryHandler) Delete(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Delete"))
// ID is URL parameter.
var err error
id := chi.URLParam(r, "id")
err = h.client.Entry.DeleteOneID(id).Exec(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.String("id", id))
NotFound(w, msg)
default:
l.Error("could-not-delete-entry", zap.Error(err), zap.String("id", id))
InternalServerError(w, nil)
}
return
}
l.Info("entry deleted", zap.String("id", id))
w.WriteHeader(http.StatusNoContent)
}
// Delete removes a ent.Fridge from the database.
func (h FridgeHandler) Delete(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Delete"))
// ID is URL parameter.
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
BadRequest(w, "id must be an integer")
return
}
err = h.client.Fridge.DeleteOneID(id).Exec(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.Int("id", id))
NotFound(w, msg)
default:
l.Error("could-not-delete-fridge", zap.Error(err), zap.Int("id", id))
InternalServerError(w, nil)
}
return
}
l.Info("fridge deleted", zap.Int("id", id))
w.WriteHeader(http.StatusNoContent)
}
// Delete removes a ent.Item from the database.
func (h ItemHandler) Delete(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Delete"))
// ID is URL parameter.
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
BadRequest(w, "id must be an integer")
return
}
err = h.client.Item.DeleteOneID(id).Exec(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.Int("id", id))
NotFound(w, msg)
default:
l.Error("could-not-delete-item", zap.Error(err), zap.Int("id", id))
InternalServerError(w, nil)
}
return
}
l.Info("item deleted", zap.Int("id", id))
w.WriteHeader(http.StatusNoContent)
}

File diff suppressed because it is too large Load Diff

View File

@ -1,185 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package http
import (
"strings"
"t/ent"
"github.com/go-chi/chi/v5"
"go.uber.org/zap"
)
// NewHandler returns a ready to use handler with all generated endpoints mounted.
func NewHandler(c *ent.Client, l *zap.Logger) chi.Router {
r := chi.NewRouter()
MountRoutes(c, l, r)
return r
}
// MountRoutes mounts all generated routes on the given router.
func MountRoutes(c *ent.Client, l *zap.Logger, r chi.Router) {
NewCompartmentHandler(c, l).MountRoutes(r)
NewEntryHandler(c, l).MountRoutes(r)
NewFridgeHandler(c, l).MountRoutes(r)
NewItemHandler(c, l).MountRoutes(r)
}
// CompartmentHandler handles http crud operations on ent.Compartment.
type CompartmentHandler struct {
client *ent.Client
log *zap.Logger
}
func NewCompartmentHandler(c *ent.Client, l *zap.Logger) *CompartmentHandler {
return &CompartmentHandler{
client: c,
log: l.With(zap.String("handler", "CompartmentHandler")),
}
}
func (h *CompartmentHandler) MountCreateRoute(r chi.Router) *CompartmentHandler {
r.Post("/compartments", h.Create)
return h
}
func (h *CompartmentHandler) MountReadRoute(r chi.Router) *CompartmentHandler {
r.Get("/compartments/{id}", h.Read)
return h
}
func (h *CompartmentHandler) MountUpdateRoute(r chi.Router) *CompartmentHandler {
r.Patch("/compartments/{id}", h.Update)
return h
}
func (h *CompartmentHandler) MountDeleteRoute(r chi.Router) *CompartmentHandler {
r.Delete("/compartments/{id}", h.Delete)
return h
}
func (h *CompartmentHandler) MountListRoute(r chi.Router) *CompartmentHandler {
r.Get("/compartments", h.List)
return h
}
func (h *CompartmentHandler) MountRoutes(r chi.Router) {
h.MountCreateRoute(r).MountReadRoute(r).MountUpdateRoute(r).MountDeleteRoute(r).MountListRoute(r)
}
// EntryHandler handles http crud operations on ent.Entry.
type EntryHandler struct {
client *ent.Client
log *zap.Logger
}
func NewEntryHandler(c *ent.Client, l *zap.Logger) *EntryHandler {
return &EntryHandler{
client: c,
log: l.With(zap.String("handler", "EntryHandler")),
}
}
func (h *EntryHandler) MountCreateRoute(r chi.Router) *EntryHandler {
r.Post("/entries", h.Create)
return h
}
func (h *EntryHandler) MountReadRoute(r chi.Router) *EntryHandler {
r.Get("/entries/{id}", h.Read)
return h
}
func (h *EntryHandler) MountUpdateRoute(r chi.Router) *EntryHandler {
r.Patch("/entries/{id}", h.Update)
return h
}
func (h *EntryHandler) MountDeleteRoute(r chi.Router) *EntryHandler {
r.Delete("/entries/{id}", h.Delete)
return h
}
func (h *EntryHandler) MountListRoute(r chi.Router) *EntryHandler {
r.Get("/entries", h.List)
return h
}
func (h *EntryHandler) MountRoutes(r chi.Router) {
h.MountCreateRoute(r).MountReadRoute(r).MountUpdateRoute(r).MountDeleteRoute(r).MountListRoute(r)
}
// FridgeHandler handles http crud operations on ent.Fridge.
type FridgeHandler struct {
client *ent.Client
log *zap.Logger
}
func NewFridgeHandler(c *ent.Client, l *zap.Logger) *FridgeHandler {
return &FridgeHandler{
client: c,
log: l.With(zap.String("handler", "FridgeHandler")),
}
}
func (h *FridgeHandler) MountCreateRoute(r chi.Router) *FridgeHandler {
r.Post("/fridges", h.Create)
return h
}
func (h *FridgeHandler) MountReadRoute(r chi.Router) *FridgeHandler {
r.Get("/fridges/{id}", h.Read)
return h
}
func (h *FridgeHandler) MountUpdateRoute(r chi.Router) *FridgeHandler {
r.Patch("/fridges/{id}", h.Update)
return h
}
func (h *FridgeHandler) MountDeleteRoute(r chi.Router) *FridgeHandler {
r.Delete("/fridges/{id}", h.Delete)
return h
}
func (h *FridgeHandler) MountListRoute(r chi.Router) *FridgeHandler {
r.Get("/fridges", h.List)
return h
}
func (h *FridgeHandler) MountRoutes(r chi.Router) {
h.MountCreateRoute(r).MountReadRoute(r).MountUpdateRoute(r).MountDeleteRoute(r).MountListRoute(r)
}
// ItemHandler handles http crud operations on ent.Item.
type ItemHandler struct {
client *ent.Client
log *zap.Logger
}
func NewItemHandler(c *ent.Client, l *zap.Logger) *ItemHandler {
return &ItemHandler{
client: c,
log: l.With(zap.String("handler", "ItemHandler")),
}
}
func (h *ItemHandler) MountCreateRoute(r chi.Router) *ItemHandler {
r.Post("/items", h.Create)
return h
}
func (h *ItemHandler) MountReadRoute(r chi.Router) *ItemHandler {
r.Get("/items/{id}", h.Read)
return h
}
func (h *ItemHandler) MountUpdateRoute(r chi.Router) *ItemHandler {
r.Patch("/items/{id}", h.Update)
return h
}
func (h *ItemHandler) MountDeleteRoute(r chi.Router) *ItemHandler {
r.Delete("/items/{id}", h.Delete)
return h
}
func (h *ItemHandler) MountListRoute(r chi.Router) *ItemHandler {
r.Get("/items", h.List)
return h
}
func (h *ItemHandler) MountRoutes(r chi.Router) {
h.MountCreateRoute(r).MountReadRoute(r).MountUpdateRoute(r).MountDeleteRoute(r).MountListRoute(r)
}
func stripEntError(err error) string {
return strings.TrimPrefix(err.Error(), "ent: ")
}
func zapFields(errs map[string]string) []zap.Field {
if errs == nil || len(errs) == 0 {
return nil
}
r := make([]zap.Field, 0)
for k, v := range errs {
r = append(r, zap.String(k, v))
}
return r
}

View File

@ -1,147 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package http
import (
"net/http"
"strconv"
"github.com/mailru/easyjson"
"go.uber.org/zap"
)
// Read fetches the ent.Compartment identified by a given url-parameter from the
// database and returns it to the client.
func (h *CompartmentHandler) List(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "List"))
q := h.client.Compartment.Query()
var err error
page := 1
if d := r.URL.Query().Get("page"); d != "" {
page, err = strconv.Atoi(d)
if err != nil {
l.Info("error parsing query parameter 'page'", zap.String("page", d), zap.Error(err))
BadRequest(w, "page must be an integer greater zero")
return
}
}
itemsPerPage := 30
if d := r.URL.Query().Get("itemsPerPage"); d != "" {
itemsPerPage, err = strconv.Atoi(d)
if err != nil {
l.Info("error parsing query parameter 'itemsPerPage'", zap.String("itemsPerPage", d), zap.Error(err))
BadRequest(w, "itemsPerPage must be an integer greater zero")
return
}
}
es, err := q.Limit(itemsPerPage).Offset((page - 1) * itemsPerPage).All(r.Context())
if err != nil {
l.Error("error fetching compartments from db", zap.Error(err))
InternalServerError(w, nil)
return
}
l.Info("compartments rendered", zap.Int("amount", len(es)))
easyjson.MarshalToHTTPResponseWriter(NewCompartment3324871446Views(es), w)
}
// Read fetches the ent.Entry identified by a given url-parameter from the
// database and returns it to the client.
func (h *EntryHandler) List(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "List"))
q := h.client.Entry.Query()
var err error
page := 1
if d := r.URL.Query().Get("page"); d != "" {
page, err = strconv.Atoi(d)
if err != nil {
l.Info("error parsing query parameter 'page'", zap.String("page", d), zap.Error(err))
BadRequest(w, "page must be an integer greater zero")
return
}
}
itemsPerPage := 30
if d := r.URL.Query().Get("itemsPerPage"); d != "" {
itemsPerPage, err = strconv.Atoi(d)
if err != nil {
l.Info("error parsing query parameter 'itemsPerPage'", zap.String("itemsPerPage", d), zap.Error(err))
BadRequest(w, "itemsPerPage must be an integer greater zero")
return
}
}
es, err := q.Limit(itemsPerPage).Offset((page - 1) * itemsPerPage).All(r.Context())
if err != nil {
l.Error("error fetching entries from db", zap.Error(err))
InternalServerError(w, nil)
return
}
l.Info("entries rendered", zap.Int("amount", len(es)))
easyjson.MarshalToHTTPResponseWriter(NewEntry2675665849Views(es), w)
}
// Read fetches the ent.Fridge identified by a given url-parameter from the
// database and returns it to the client.
func (h *FridgeHandler) List(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "List"))
q := h.client.Fridge.Query()
var err error
page := 1
if d := r.URL.Query().Get("page"); d != "" {
page, err = strconv.Atoi(d)
if err != nil {
l.Info("error parsing query parameter 'page'", zap.String("page", d), zap.Error(err))
BadRequest(w, "page must be an integer greater zero")
return
}
}
itemsPerPage := 30
if d := r.URL.Query().Get("itemsPerPage"); d != "" {
itemsPerPage, err = strconv.Atoi(d)
if err != nil {
l.Info("error parsing query parameter 'itemsPerPage'", zap.String("itemsPerPage", d), zap.Error(err))
BadRequest(w, "itemsPerPage must be an integer greater zero")
return
}
}
es, err := q.Limit(itemsPerPage).Offset((page - 1) * itemsPerPage).All(r.Context())
if err != nil {
l.Error("error fetching fridges from db", zap.Error(err))
InternalServerError(w, nil)
return
}
l.Info("fridges rendered", zap.Int("amount", len(es)))
easyjson.MarshalToHTTPResponseWriter(NewFridge2211356377Views(es), w)
}
// Read fetches the ent.Item identified by a given url-parameter from the
// database and returns it to the client.
func (h *ItemHandler) List(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "List"))
q := h.client.Item.Query()
var err error
page := 1
if d := r.URL.Query().Get("page"); d != "" {
page, err = strconv.Atoi(d)
if err != nil {
l.Info("error parsing query parameter 'page'", zap.String("page", d), zap.Error(err))
BadRequest(w, "page must be an integer greater zero")
return
}
}
itemsPerPage := 30
if d := r.URL.Query().Get("itemsPerPage"); d != "" {
itemsPerPage, err = strconv.Atoi(d)
if err != nil {
l.Info("error parsing query parameter 'itemsPerPage'", zap.String("itemsPerPage", d), zap.Error(err))
BadRequest(w, "itemsPerPage must be an integer greater zero")
return
}
}
es, err := q.Limit(itemsPerPage).Offset((page - 1) * itemsPerPage).All(r.Context())
if err != nil {
l.Error("error fetching items from db", zap.Error(err))
InternalServerError(w, nil)
return
}
l.Info("items rendered", zap.Int("amount", len(es)))
easyjson.MarshalToHTTPResponseWriter(NewItem1548468123Views(es), w)
}

View File

@ -1,149 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package http
import (
"net/http"
"strconv"
"t/ent"
"t/ent/compartment"
"t/ent/entry"
"t/ent/fridge"
"t/ent/item"
"github.com/go-chi/chi/v5"
"github.com/mailru/easyjson"
"go.uber.org/zap"
)
// Read fetches the ent.Compartment identified by a given url-parameter from the
// database and renders it to the client.
func (h *CompartmentHandler) Read(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Read"))
// ID is URL parameter.
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
BadRequest(w, "id must be an integer")
return
}
// Create the query to fetch the Compartment
q := h.client.Compartment.Query().Where(compartment.ID(id))
e, err := q.Only(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.Int("id", id))
NotFound(w, msg)
case ent.IsNotSingular(err):
msg := stripEntError(err)
l.Error(msg, zap.Error(err), zap.Int("id", id))
BadRequest(w, msg)
default:
l.Error("could not read compartment", zap.Error(err), zap.Int("id", id))
InternalServerError(w, nil)
}
return
}
l.Info("compartment rendered", zap.Int("id", id))
easyjson.MarshalToHTTPResponseWriter(NewCompartment3324871446View(e), w)
}
// Read fetches the ent.Entry identified by a given url-parameter from the
// database and renders it to the client.
func (h *EntryHandler) Read(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Read"))
// ID is URL parameter.
var err error
id := chi.URLParam(r, "id")
// Create the query to fetch the Entry
q := h.client.Entry.Query().Where(entry.ID(id))
e, err := q.Only(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.String("id", id))
NotFound(w, msg)
case ent.IsNotSingular(err):
msg := stripEntError(err)
l.Error(msg, zap.Error(err), zap.String("id", id))
BadRequest(w, msg)
default:
l.Error("could not read entry", zap.Error(err), zap.String("id", id))
InternalServerError(w, nil)
}
return
}
l.Info("entry rendered", zap.String("id", id))
easyjson.MarshalToHTTPResponseWriter(NewEntry2675665849View(e), w)
}
// Read fetches the ent.Fridge identified by a given url-parameter from the
// database and renders it to the client.
func (h *FridgeHandler) Read(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Read"))
// ID is URL parameter.
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
BadRequest(w, "id must be an integer")
return
}
// Create the query to fetch the Fridge
q := h.client.Fridge.Query().Where(fridge.ID(id))
e, err := q.Only(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.Int("id", id))
NotFound(w, msg)
case ent.IsNotSingular(err):
msg := stripEntError(err)
l.Error(msg, zap.Error(err), zap.Int("id", id))
BadRequest(w, msg)
default:
l.Error("could not read fridge", zap.Error(err), zap.Int("id", id))
InternalServerError(w, nil)
}
return
}
l.Info("fridge rendered", zap.Int("id", id))
easyjson.MarshalToHTTPResponseWriter(NewFridge2211356377View(e), w)
}
// Read fetches the ent.Item identified by a given url-parameter from the
// database and renders it to the client.
func (h *ItemHandler) Read(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Read"))
// ID is URL parameter.
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
BadRequest(w, "id must be an integer")
return
}
// Create the query to fetch the Item
q := h.client.Item.Query().Where(item.ID(id))
e, err := q.Only(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.Int("id", id))
NotFound(w, msg)
case ent.IsNotSingular(err):
msg := stripEntError(err)
l.Error(msg, zap.Error(err), zap.Int("id", id))
BadRequest(w, msg)
default:
l.Error("could not read item", zap.Error(err), zap.Int("id", id))
InternalServerError(w, nil)
}
return
}
l.Info("item rendered", zap.Int("id", id))
easyjson.MarshalToHTTPResponseWriter(NewItem1548468123View(e), w)
}

View File

@ -1,3 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package http

View File

@ -1,42 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package http
import (
"time"
)
// Payload of a ent.Compartment create request.
type CompartmentCreateRequest struct {
}
// Payload of a ent.Compartment update request.
type CompartmentUpdateRequest struct {
}
// Payload of a ent.Entry create request.
type EntryCreateRequest struct {
User *string `json:"user"`
First *int `json:"first"`
CreatedAt *time.Time `json:"created_at"`
}
// Payload of a ent.Entry update request.
type EntryUpdateRequest struct {
}
// Payload of a ent.Fridge create request.
type FridgeCreateRequest struct {
}
// Payload of a ent.Fridge update request.
type FridgeUpdateRequest struct {
}
// Payload of a ent.Item create request.
type ItemCreateRequest struct {
}
// Payload of a ent.Item update request.
type ItemUpdateRequest struct {
}

View File

@ -1,200 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package http
import (
"net/http"
"strconv"
"t/ent"
"time"
"github.com/mailru/easyjson"
)
// Basic HTTP Error Response
type ErrResponse struct {
Code int `json:"code"` // http response status code
Status string `json:"status"` // user-level status message
Errors interface{} `json:"errors,omitempty"` // application-level error
}
func (e ErrResponse) MarshalToHTTPResponseWriter(w http.ResponseWriter) (int, error) {
d, err := easyjson.Marshal(e)
if err != nil {
return 0, err
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Content-Length", strconv.Itoa(len(d)))
w.WriteHeader(e.Code)
return w.Write(d)
}
func BadRequest(w http.ResponseWriter, msg interface{}) (int, error) {
return ErrResponse{
Code: http.StatusBadRequest,
Status: http.StatusText(http.StatusBadRequest),
Errors: msg,
}.MarshalToHTTPResponseWriter(w)
}
func Conflict(w http.ResponseWriter, msg interface{}) (int, error) {
return ErrResponse{
Code: http.StatusConflict,
Status: http.StatusText(http.StatusConflict),
Errors: msg,
}.MarshalToHTTPResponseWriter(w)
}
func Forbidden(w http.ResponseWriter, msg interface{}) (int, error) {
return ErrResponse{
Code: http.StatusForbidden,
Status: http.StatusText(http.StatusForbidden),
Errors: msg,
}.MarshalToHTTPResponseWriter(w)
}
func InternalServerError(w http.ResponseWriter, msg interface{}) (int, error) {
return ErrResponse{
Code: http.StatusInternalServerError,
Status: http.StatusText(http.StatusInternalServerError),
Errors: msg,
}.MarshalToHTTPResponseWriter(w)
}
func NotFound(w http.ResponseWriter, msg interface{}) (int, error) {
return ErrResponse{
Code: http.StatusNotFound,
Status: http.StatusText(http.StatusNotFound),
Errors: msg,
}.MarshalToHTTPResponseWriter(w)
}
func Unauthorized(w http.ResponseWriter, msg interface{}) (int, error) {
return ErrResponse{
Code: http.StatusUnauthorized,
Status: http.StatusText(http.StatusUnauthorized),
Errors: msg,
}.MarshalToHTTPResponseWriter(w)
}
type (
// Compartment3324871446View represents the data serialized for the following serialization group combinations:
// []
Compartment3324871446View struct {
ID int `json:"id,omitempty"`
}
Compartment3324871446Views []*Compartment3324871446View
)
func NewCompartment3324871446View(e *ent.Compartment) *Compartment3324871446View {
if e == nil {
return nil
}
return &Compartment3324871446View{
ID: e.ID,
}
}
func NewCompartment3324871446Views(es []*ent.Compartment) Compartment3324871446Views {
if len(es) == 0 {
return nil
}
r := make(Compartment3324871446Views, len(es))
for i, e := range es {
r[i] = NewCompartment3324871446View(e)
}
return r
}
type (
// Entry2675665849View represents the data serialized for the following serialization group combinations:
// []
Entry2675665849View struct {
ID string `json:"id,omitempty"`
User string `json:"user,omitempty"`
First int `json:"first,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
}
Entry2675665849Views []*Entry2675665849View
)
func NewEntry2675665849View(e *ent.Entry) *Entry2675665849View {
if e == nil {
return nil
}
return &Entry2675665849View{
ID: e.ID,
User: e.User,
First: e.First,
CreatedAt: e.CreatedAt,
}
}
func NewEntry2675665849Views(es []*ent.Entry) Entry2675665849Views {
if len(es) == 0 {
return nil
}
r := make(Entry2675665849Views, len(es))
for i, e := range es {
r[i] = NewEntry2675665849View(e)
}
return r
}
type (
// Fridge2211356377View represents the data serialized for the following serialization group combinations:
// []
Fridge2211356377View struct {
ID int `json:"id,omitempty"`
}
Fridge2211356377Views []*Fridge2211356377View
)
func NewFridge2211356377View(e *ent.Fridge) *Fridge2211356377View {
if e == nil {
return nil
}
return &Fridge2211356377View{
ID: e.ID,
}
}
func NewFridge2211356377Views(es []*ent.Fridge) Fridge2211356377Views {
if len(es) == 0 {
return nil
}
r := make(Fridge2211356377Views, len(es))
for i, e := range es {
r[i] = NewFridge2211356377View(e)
}
return r
}
type (
// Item1548468123View represents the data serialized for the following serialization group combinations:
// []
Item1548468123View struct {
ID int `json:"id,omitempty"`
}
Item1548468123Views []*Item1548468123View
)
func NewItem1548468123View(e *ent.Item) *Item1548468123View {
if e == nil {
return nil
}
return &Item1548468123View{
ID: e.ID,
}
}
func NewItem1548468123Views(es []*ent.Item) Item1548468123Views {
if len(es) == 0 {
return nil
}
r := make(Item1548468123Views, len(es))
for i, e := range es {
r[i] = NewItem1548468123View(e)
}
return r
}

View File

@ -1,260 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package http
import (
"net/http"
"strconv"
"t/ent"
"t/ent/compartment"
"t/ent/entry"
"t/ent/fridge"
"t/ent/item"
"github.com/go-chi/chi/v5"
"github.com/mailru/easyjson"
"go.uber.org/zap"
)
// Update updates a given ent.Compartment and saves the changes to the database.
func (h CompartmentHandler) Update(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Update"))
// ID is URL parameter.
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
BadRequest(w, "id must be an integer")
return
}
// Get the post data.
var d CompartmentUpdateRequest
if err := easyjson.UnmarshalFromReader(r.Body, &d); err != nil {
l.Error("error decoding json", zap.Error(err))
BadRequest(w, "invalid json string")
return
}
// Save the data.
b := h.client.Compartment.UpdateOneID(id)
// Store in database.
e, err := b.Save(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.Int("id", id))
NotFound(w, msg)
case ent.IsNotSingular(err):
msg := stripEntError(err)
l.Error(msg, zap.Error(err), zap.Int("id", id))
BadRequest(w, msg)
default:
l.Error("could-not-update-compartment", zap.Error(err), zap.Int("id", id))
InternalServerError(w, nil)
}
return
}
// Reload entry.
q := h.client.Compartment.Query().Where(compartment.ID(e.ID))
e, err = q.Only(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.Int("id", id))
NotFound(w, msg)
case ent.IsNotSingular(err):
msg := stripEntError(err)
l.Error(msg, zap.Error(err), zap.Int("id", id))
BadRequest(w, msg)
default:
l.Error("could-not-read-compartment", zap.Error(err), zap.Int("id", id))
InternalServerError(w, nil)
}
return
}
l.Info("compartment rendered", zap.Int("id", id))
easyjson.MarshalToHTTPResponseWriter(NewCompartment3324871446View(e), w)
}
// Update updates a given ent.Entry and saves the changes to the database.
func (h EntryHandler) Update(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Update"))
// ID is URL parameter.
var err error
id := chi.URLParam(r, "id")
// Get the post data.
var d EntryUpdateRequest
if err := easyjson.UnmarshalFromReader(r.Body, &d); err != nil {
l.Error("error decoding json", zap.Error(err))
BadRequest(w, "invalid json string")
return
}
// Validate the data.
errs := make(map[string]string)
if len(errs) > 0 {
l.Info("validation failed", zapFields(errs)...)
BadRequest(w, errs)
return
}
// Save the data.
b := h.client.Entry.UpdateOneID(id)
// Store in database.
e, err := b.Save(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.String("id", id))
NotFound(w, msg)
case ent.IsNotSingular(err):
msg := stripEntError(err)
l.Error(msg, zap.Error(err), zap.String("id", id))
BadRequest(w, msg)
default:
l.Error("could-not-update-entry", zap.Error(err), zap.String("id", id))
InternalServerError(w, nil)
}
return
}
// Reload entry.
q := h.client.Entry.Query().Where(entry.ID(e.ID))
e, err = q.Only(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.String("id", id))
NotFound(w, msg)
case ent.IsNotSingular(err):
msg := stripEntError(err)
l.Error(msg, zap.Error(err), zap.String("id", id))
BadRequest(w, msg)
default:
l.Error("could-not-read-entry", zap.Error(err), zap.String("id", id))
InternalServerError(w, nil)
}
return
}
l.Info("entry rendered", zap.String("id", id))
easyjson.MarshalToHTTPResponseWriter(NewEntry2675665849View(e), w)
}
// Update updates a given ent.Fridge and saves the changes to the database.
func (h FridgeHandler) Update(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Update"))
// ID is URL parameter.
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
BadRequest(w, "id must be an integer")
return
}
// Get the post data.
var d FridgeUpdateRequest
if err := easyjson.UnmarshalFromReader(r.Body, &d); err != nil {
l.Error("error decoding json", zap.Error(err))
BadRequest(w, "invalid json string")
return
}
// Save the data.
b := h.client.Fridge.UpdateOneID(id)
// Store in database.
e, err := b.Save(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.Int("id", id))
NotFound(w, msg)
case ent.IsNotSingular(err):
msg := stripEntError(err)
l.Error(msg, zap.Error(err), zap.Int("id", id))
BadRequest(w, msg)
default:
l.Error("could-not-update-fridge", zap.Error(err), zap.Int("id", id))
InternalServerError(w, nil)
}
return
}
// Reload entry.
q := h.client.Fridge.Query().Where(fridge.ID(e.ID))
e, err = q.Only(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.Int("id", id))
NotFound(w, msg)
case ent.IsNotSingular(err):
msg := stripEntError(err)
l.Error(msg, zap.Error(err), zap.Int("id", id))
BadRequest(w, msg)
default:
l.Error("could-not-read-fridge", zap.Error(err), zap.Int("id", id))
InternalServerError(w, nil)
}
return
}
l.Info("fridge rendered", zap.Int("id", id))
easyjson.MarshalToHTTPResponseWriter(NewFridge2211356377View(e), w)
}
// Update updates a given ent.Item and saves the changes to the database.
func (h ItemHandler) Update(w http.ResponseWriter, r *http.Request) {
l := h.log.With(zap.String("method", "Update"))
// ID is URL parameter.
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
l.Error("error getting id from url parameter", zap.String("id", chi.URLParam(r, "id")), zap.Error(err))
BadRequest(w, "id must be an integer")
return
}
// Get the post data.
var d ItemUpdateRequest
if err := easyjson.UnmarshalFromReader(r.Body, &d); err != nil {
l.Error("error decoding json", zap.Error(err))
BadRequest(w, "invalid json string")
return
}
// Save the data.
b := h.client.Item.UpdateOneID(id)
// Store in database.
e, err := b.Save(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.Int("id", id))
NotFound(w, msg)
case ent.IsNotSingular(err):
msg := stripEntError(err)
l.Error(msg, zap.Error(err), zap.Int("id", id))
BadRequest(w, msg)
default:
l.Error("could-not-update-item", zap.Error(err), zap.Int("id", id))
InternalServerError(w, nil)
}
return
}
// Reload entry.
q := h.client.Item.Query().Where(item.ID(e.ID))
e, err = q.Only(r.Context())
if err != nil {
switch {
case ent.IsNotFound(err):
msg := stripEntError(err)
l.Info(msg, zap.Error(err), zap.Int("id", id))
NotFound(w, msg)
case ent.IsNotSingular(err):
msg := stripEntError(err)
l.Error(msg, zap.Error(err), zap.Int("id", id))
BadRequest(w, msg)
default:
l.Error("could-not-read-item", zap.Error(err), zap.Int("id", id))
InternalServerError(w, nil)
}
return
}
l.Info("item rendered", zap.Int("id", id))
easyjson.MarshalToHTTPResponseWriter(NewItem1548468123View(e), w)
}

View File

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT.
// Code generated by ent, DO NOT EDIT.
package migrate
@ -28,9 +28,6 @@ var (
// and therefore, it's recommended to enable this option to get more
// flexibility in the schema changes.
WithDropIndex = schema.WithDropIndex
// WithFixture sets the foreign-key renaming option to the migration when upgrading
// ent from v0.1.0 (issue-#285). Defaults to false.
WithFixture = schema.WithFixture
// WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
WithForeignKeys = schema.WithForeignKeys
)
@ -45,11 +42,16 @@ 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...)
return migrate.Create(ctx, tables...)
}
// WriteTo writes the schema changes to w instead of running them against the database.
@ -57,15 +59,6 @@ func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error
// 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 {
drv := &schema.WriteDriver{
Writer: w,
Driver: s.drv,
}
migrate, err := schema.NewMigrate(drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", err)
}
return migrate.Create(ctx, Tables...)
return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...)
}

View File

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT.
// Code generated by ent, DO NOT EDIT.
package migrate
@ -8,39 +8,87 @@ import (
)
var (
// CardsColumns holds the columns for the "cards" table.
CardsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "card", Type: field.TypeInt, Nullable: true},
{Name: "status", Type: field.TypeString, Nullable: true},
{Name: "cp", Type: field.TypeInt, Nullable: true},
{Name: "url", Type: field.TypeString, Nullable: true, Default: "https://card.syui.ai"},
{Name: "created_at", Type: field.TypeTime, Nullable: true},
{Name: "user_card", Type: field.TypeInt},
}
// CardsTable holds the schema information for the "cards" table.
CardsTable = &schema.Table{
Name: "cards",
Columns: CardsColumns,
PrimaryKey: []*schema.Column{CardsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "cards_users_card",
Columns: []*schema.Column{CardsColumns[6]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
},
}
// GroupsColumns holds the columns for the "groups" table.
GroupsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString},
}
// GroupsTable holds the schema information for the "groups" table.
GroupsTable = &schema.Table{
Name: "groups",
Columns: GroupsColumns,
PrimaryKey: []*schema.Column{GroupsColumns[0]},
Indexes: []*schema.Index{
{
Name: "group_name",
Unique: true,
Columns: []*schema.Column{GroupsColumns[1]},
},
},
}
// UsersColumns holds the columns for the "users" table.
UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "user", Type: field.TypeString, Unique: true, Size: 7},
{Name: "chara", Type: field.TypeString, Nullable: true, Default: "ponta"},
{Name: "skill", Type: field.TypeInt, Nullable: true, Default: 7},
{Name: "hp", Type: field.TypeInt, Nullable: true, Default: 7},
{Name: "attack", Type: field.TypeInt, Nullable: true, Default: 8},
{Name: "defense", Type: field.TypeInt, Nullable: true, Default: 19},
{Name: "critical", Type: field.TypeInt, Nullable: true, Default: 7},
{Name: "battle", Type: field.TypeInt, Nullable: true, Default: 1},
{Name: "win", Type: field.TypeInt, Nullable: true, Default: 0},
{Name: "day", Type: field.TypeInt, Nullable: true, Default: 0},
{Name: "percentage", Type: field.TypeFloat64, Nullable: true, Default: 0},
{Name: "limit", Type: field.TypeBool, Nullable: true, Default: false},
{Name: "status", Type: field.TypeString, Nullable: true, Default: "normal"},
{Name: "comment", Type: field.TypeString, Nullable: true, Default: ""},
{Name: "username", Type: field.TypeString, Unique: true, Size: 30},
{Name: "created_at", Type: field.TypeTime, Nullable: true},
{Name: "next", Type: field.TypeString, Nullable: true, Default: "20220617"},
{Name: "updated_at", Type: field.TypeTime, Nullable: true},
{Name: "url", Type: field.TypeString, Nullable: true, Default: "https://syui.cf/api"},
{Name: "next", Type: field.TypeString, Nullable: true, Default: "20230404"},
{Name: "group_users", Type: field.TypeInt, Nullable: true},
}
// UsersTable holds the schema information for the "users" table.
UsersTable = &schema.Table{
Name: "users",
Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "users_groups_users",
Columns: []*schema.Column{UsersColumns[5]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.SetNull,
},
},
Indexes: []*schema.Index{
{
Name: "user_username",
Unique: true,
Columns: []*schema.Column{UsersColumns[1]},
},
},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
CardsTable,
GroupsTable,
UsersTable,
}
)
func init() {
CardsTable.ForeignKeys[0].RefTable = UsersTable
UsersTable.ForeignKeys[0].RefTable = GroupsTable
}

File diff suppressed because it is too large Load Diff

View File

@ -3,132 +3,195 @@
package ogent
import (
"bytes"
"context"
"fmt"
"io"
"math"
"math/big"
"math/bits"
"net"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/google/uuid"
"github.com/ogen-go/ogen/conv"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/json"
"github.com/ogen-go/ogen/otelogen"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/metric/instrument"
"go.opentelemetry.io/otel/trace"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/middleware"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/otelogen"
)
// No-op definition for keeping imports.
var (
_ = context.Background()
_ = fmt.Stringer(nil)
_ = strings.Builder{}
_ = errors.Is
_ = sort.Ints
_ = http.MethodGet
_ = io.Copy
_ = json.Marshal
_ = bytes.NewReader
_ = strconv.ParseInt
_ = time.Time{}
_ = conv.ToInt32
_ = uuid.UUID{}
_ = uri.PathEncoder{}
_ = url.URL{}
_ = math.Mod
_ = bits.LeadingZeros64
_ = big.Rat{}
_ = validate.Int{}
_ = ht.NewRequest
_ = net.IP{}
_ = otelogen.Version
_ = attribute.KeyValue{}
_ = trace.TraceIDFromHex
_ = otel.GetTracerProvider
_ = metric.NewNoopMeterProvider
_ = regexp.MustCompile
_ = jx.Null
_ = sync.Pool{}
_ = codes.Unset
// Allocate option closure once.
clientSpanKind = trace.WithSpanKind(trace.SpanKindClient)
// Allocate option closure once.
serverSpanKind = trace.WithSpanKind(trace.SpanKindServer)
)
// bufPool is pool of bytes.Buffer for encoding and decoding.
var bufPool = &sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
type (
optionFunc[C any] func(*C)
otelOptionFunc func(*otelConfig)
)
// getBuf returns buffer from pool.
func getBuf() *bytes.Buffer {
return bufPool.Get().(*bytes.Buffer)
}
// putBuf puts buffer to pool.
func putBuf(b *bytes.Buffer) {
b.Reset()
bufPool.Put(b)
}
type config struct {
type otelConfig struct {
TracerProvider trace.TracerProvider
Tracer trace.Tracer
MeterProvider metric.MeterProvider
Meter metric.Meter
Client ht.Client
NotFound http.HandlerFunc
}
func newConfig(opts ...Option) config {
cfg := config{
TracerProvider: otel.GetTracerProvider(),
MeterProvider: metric.NewNoopMeterProvider(),
Client: http.DefaultClient,
NotFound: http.NotFound,
func (cfg *otelConfig) initOTEL() {
if cfg.TracerProvider == nil {
cfg.TracerProvider = otel.GetTracerProvider()
}
for _, opt := range opts {
opt.apply(&cfg)
if cfg.MeterProvider == nil {
cfg.MeterProvider = metric.NewNoopMeterProvider()
}
cfg.Tracer = cfg.TracerProvider.Tracer(otelogen.Name,
trace.WithInstrumentationVersion(otelogen.SemVersion()),
)
cfg.Meter = cfg.MeterProvider.Meter(otelogen.Name)
}
// ErrorHandler is error handler.
type ErrorHandler = ogenerrors.ErrorHandler
type serverConfig struct {
otelConfig
NotFound http.HandlerFunc
MethodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)
ErrorHandler ErrorHandler
Prefix string
Middleware Middleware
MaxMultipartMemory int64
}
// ServerOption is server config option.
type ServerOption interface {
applyServer(*serverConfig)
}
var _ = []ServerOption{
(optionFunc[serverConfig])(nil),
(otelOptionFunc)(nil),
}
func (o optionFunc[C]) applyServer(c *C) {
o(c)
}
func (o otelOptionFunc) applyServer(c *serverConfig) {
o(&c.otelConfig)
}
func newServerConfig(opts ...ServerOption) serverConfig {
cfg := serverConfig{
NotFound: http.NotFound,
MethodNotAllowed: func(w http.ResponseWriter, r *http.Request, allowed string) {
w.Header().Set("Allow", allowed)
w.WriteHeader(http.StatusMethodNotAllowed)
},
ErrorHandler: ogenerrors.DefaultErrorHandler,
Middleware: nil,
MaxMultipartMemory: 32 << 20, // 32 MB
}
for _, opt := range opts {
opt.applyServer(&cfg)
}
cfg.initOTEL()
return cfg
}
type Option interface {
apply(*config)
type baseServer struct {
cfg serverConfig
requests instrument.Int64Counter
errors instrument.Int64Counter
duration instrument.Int64Histogram
}
type optionFunc func(*config)
func (s baseServer) notFound(w http.ResponseWriter, r *http.Request) {
s.cfg.NotFound(w, r)
}
func (o optionFunc) apply(c *config) {
func (s baseServer) notAllowed(w http.ResponseWriter, r *http.Request, allowed string) {
s.cfg.MethodNotAllowed(w, r, allowed)
}
func (cfg serverConfig) baseServer() (s baseServer, err error) {
s = baseServer{cfg: cfg}
if s.requests, err = s.cfg.Meter.Int64Counter(otelogen.ServerRequestCount); err != nil {
return s, err
}
if s.errors, err = s.cfg.Meter.Int64Counter(otelogen.ServerErrorsCount); err != nil {
return s, err
}
if s.duration, err = s.cfg.Meter.Int64Histogram(otelogen.ServerDuration); err != nil {
return s, err
}
return s, nil
}
type clientConfig struct {
otelConfig
Client ht.Client
}
// ClientOption is client config option.
type ClientOption interface {
applyClient(*clientConfig)
}
var _ = []ClientOption{
(optionFunc[clientConfig])(nil),
(otelOptionFunc)(nil),
}
func (o optionFunc[C]) applyClient(c *C) {
o(c)
}
func (o otelOptionFunc) applyClient(c *clientConfig) {
o(&c.otelConfig)
}
func newClientConfig(opts ...ClientOption) clientConfig {
cfg := clientConfig{
Client: http.DefaultClient,
}
for _, opt := range opts {
opt.applyClient(&cfg)
}
cfg.initOTEL()
return cfg
}
type baseClient struct {
cfg clientConfig
requests instrument.Int64Counter
errors instrument.Int64Counter
duration instrument.Int64Histogram
}
func (cfg clientConfig) baseClient() (c baseClient, err error) {
c = baseClient{cfg: cfg}
if c.requests, err = c.cfg.Meter.Int64Counter(otelogen.ClientRequestCount); err != nil {
return c, err
}
if c.errors, err = c.cfg.Meter.Int64Counter(otelogen.ClientErrorsCount); err != nil {
return c, err
}
if c.duration, err = c.cfg.Meter.Int64Histogram(otelogen.ClientDuration); err != nil {
return c, err
}
return c, nil
}
// Option is config option.
type Option interface {
ServerOption
ClientOption
}
// WithTracerProvider specifies a tracer provider to use for creating a tracer.
//
// If none is specified, the global provider is used.
func WithTracerProvider(provider trace.TracerProvider) Option {
return optionFunc(func(cfg *config) {
return otelOptionFunc(func(cfg *otelConfig) {
if provider != nil {
cfg.TracerProvider = provider
}
@ -139,7 +202,7 @@ func WithTracerProvider(provider trace.TracerProvider) Option {
//
// If none is specified, the metric.NewNoopMeterProvider is used.
func WithMeterProvider(provider metric.MeterProvider) Option {
return optionFunc(func(cfg *config) {
return otelOptionFunc(func(cfg *otelConfig) {
if provider != nil {
cfg.MeterProvider = provider
}
@ -147,19 +210,68 @@ func WithMeterProvider(provider metric.MeterProvider) Option {
}
// WithClient specifies http client to use.
func WithClient(client ht.Client) Option {
return optionFunc(func(cfg *config) {
func WithClient(client ht.Client) ClientOption {
return optionFunc[clientConfig](func(cfg *clientConfig) {
if client != nil {
cfg.Client = client
}
})
}
// WithNotFound specifies http handler to use.
func WithNotFound(notFound http.HandlerFunc) Option {
return optionFunc(func(cfg *config) {
// WithNotFound specifies Not Found handler to use.
func WithNotFound(notFound http.HandlerFunc) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
if notFound != nil {
cfg.NotFound = notFound
}
})
}
// WithMethodNotAllowed specifies Method Not Allowed handler to use.
func WithMethodNotAllowed(methodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
if methodNotAllowed != nil {
cfg.MethodNotAllowed = methodNotAllowed
}
})
}
// WithErrorHandler specifies error handler to use.
func WithErrorHandler(h ErrorHandler) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
if h != nil {
cfg.ErrorHandler = h
}
})
}
// WithPathPrefix specifies server path prefix.
func WithPathPrefix(prefix string) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
cfg.Prefix = prefix
})
}
// WithMiddleware specifies middlewares to use.
func WithMiddleware(m ...Middleware) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
switch len(m) {
case 0:
cfg.Middleware = nil
case 1:
cfg.Middleware = m[0]
default:
cfg.Middleware = middleware.ChainMiddlewares(m...)
}
})
}
// WithMaxMultipartMemory specifies limit of memory for storing file parts.
// File parts which can't be stored in memory will be stored on disk in temporary files.
func WithMaxMultipartMemory(max int64) ServerOption {
return optionFunc[serverConfig](func(cfg *serverConfig) {
if max > 0 {
cfg.MaxMultipartMemory = max
}
})
}

File diff suppressed because it is too large Load Diff

View File

@ -1,71 +0,0 @@
// Code generated by ogen, DO NOT EDIT.
package ogent
import (
"bytes"
"context"
"fmt"
"io"
"math"
"math/big"
"math/bits"
"net"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/google/uuid"
"github.com/ogen-go/ogen/conv"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/json"
"github.com/ogen-go/ogen/otelogen"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
// No-op definition for keeping imports.
var (
_ = context.Background()
_ = fmt.Stringer(nil)
_ = strings.Builder{}
_ = errors.Is
_ = sort.Ints
_ = http.MethodGet
_ = io.Copy
_ = json.Marshal
_ = bytes.NewReader
_ = strconv.ParseInt
_ = time.Time{}
_ = conv.ToInt32
_ = uuid.UUID{}
_ = uri.PathEncoder{}
_ = url.URL{}
_ = math.Mod
_ = bits.LeadingZeros64
_ = big.Rat{}
_ = validate.Int{}
_ = ht.NewRequest
_ = net.IP{}
_ = otelogen.Version
_ = attribute.KeyValue{}
_ = trace.TraceIDFromHex
_ = otel.GetTracerProvider
_ = metric.NewNoopMeterProvider
_ = regexp.MustCompile
_ = jx.Null
_ = sync.Pool{}
_ = codes.Unset
)

File diff suppressed because it is too large Load Diff

View File

@ -1,22 +1,74 @@
// Code generated by ogen, DO NOT EDIT.
package ogent
type CreateUsersRes interface {
createUsersRes()
type CreateCardRes interface {
createCardRes()
}
type DeleteUsersRes interface {
deleteUsersRes()
type CreateGroupRes interface {
createGroupRes()
}
type ListUsersRes interface {
listUsersRes()
type CreateUserRes interface {
createUserRes()
}
type ReadUsersRes interface {
readUsersRes()
type DeleteCardRes interface {
deleteCardRes()
}
type UpdateUsersRes interface {
updateUsersRes()
type DeleteGroupRes interface {
deleteGroupRes()
}
type DeleteUserRes interface {
deleteUserRes()
}
type ListCardRes interface {
listCardRes()
}
type ListGroupRes interface {
listGroupRes()
}
type ListGroupUsersRes interface {
listGroupUsersRes()
}
type ListUserCardRes interface {
listUserCardRes()
}
type ListUserRes interface {
listUserRes()
}
type ReadCardOwnerRes interface {
readCardOwnerRes()
}
type ReadCardRes interface {
readCardRes()
}
type ReadGroupRes interface {
readGroupRes()
}
type ReadUserRes interface {
readUserRes()
}
type UpdateCardRes interface {
updateCardRes()
}
type UpdateGroupRes interface {
updateGroupRes()
}
type UpdateUserRes interface {
updateUserRes()
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,10 @@
// Code generated by ogen, DO NOT EDIT.
package ogent
import (
"github.com/ogen-go/ogen/middleware"
)
// Middleware is middleware type.
type Middleware = middleware.Middleware

View File

@ -1,339 +0,0 @@
// Code generated by ogen, DO NOT EDIT.
package ogent
import (
"bytes"
"context"
"fmt"
"io"
"math"
"math/big"
"math/bits"
"net"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/google/uuid"
"github.com/ogen-go/ogen/conv"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/json"
"github.com/ogen-go/ogen/otelogen"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
// No-op definition for keeping imports.
var (
_ = context.Background()
_ = fmt.Stringer(nil)
_ = strings.Builder{}
_ = errors.Is
_ = sort.Ints
_ = http.MethodGet
_ = io.Copy
_ = json.Marshal
_ = bytes.NewReader
_ = strconv.ParseInt
_ = time.Time{}
_ = conv.ToInt32
_ = uuid.UUID{}
_ = uri.PathEncoder{}
_ = url.URL{}
_ = math.Mod
_ = bits.LeadingZeros64
_ = big.Rat{}
_ = validate.Int{}
_ = ht.NewRequest
_ = net.IP{}
_ = otelogen.Version
_ = attribute.KeyValue{}
_ = trace.TraceIDFromHex
_ = otel.GetTracerProvider
_ = metric.NewNoopMeterProvider
_ = regexp.MustCompile
_ = jx.Null
_ = sync.Pool{}
_ = codes.Unset
)
func decodeDeleteUsersParams(args [1]string, r *http.Request) (DeleteUsersParams, error) {
var (
params DeleteUsersParams
)
// Decode path: id.
{
param := args[0]
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
s, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToInt(s)
if err != nil {
return err
}
params.ID = c
return nil
}(); err != nil {
return params, err
}
} else {
return params, errors.New("path: id: not specified")
}
}
return params, nil
}
func decodeDrawDoneParams(args [1]string, r *http.Request) (DrawDoneParams, error) {
var (
params DrawDoneParams
)
// Decode path: id.
{
param := args[0]
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
s, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToInt(s)
if err != nil {
return err
}
params.ID = c
return nil
}(); err != nil {
return params, err
}
} else {
return params, errors.New("path: id: not specified")
}
}
return params, nil
}
func decodeDrawStartParams(args [1]string, r *http.Request) (DrawStartParams, error) {
var (
params DrawStartParams
)
// Decode path: id.
{
param := args[0]
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
s, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToInt(s)
if err != nil {
return err
}
params.ID = c
return nil
}(); err != nil {
return params, err
}
} else {
return params, errors.New("path: id: not specified")
}
}
return params, nil
}
func decodeListUsersParams(args [0]string, r *http.Request) (ListUsersParams, error) {
var (
params ListUsersParams
queryArgs = r.URL.Query()
)
// Decode query: page.
{
values, ok := queryArgs["page"]
if ok {
d := uri.NewQueryDecoder(uri.QueryDecoderConfig{
Values: values,
Style: uri.QueryStyleForm,
Explode: true,
})
if err := func() error {
var paramsDotPageVal int
if err := func() error {
s, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToInt(s)
if err != nil {
return err
}
paramsDotPageVal = c
return nil
}(); err != nil {
return err
}
params.Page.SetTo(paramsDotPageVal)
return nil
}(); err != nil {
return params, errors.Wrap(err, "query: page: parse")
}
}
}
// Decode query: itemsPerPage.
{
values, ok := queryArgs["itemsPerPage"]
if ok {
d := uri.NewQueryDecoder(uri.QueryDecoderConfig{
Values: values,
Style: uri.QueryStyleForm,
Explode: true,
})
if err := func() error {
var paramsDotItemsPerPageVal int
if err := func() error {
s, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToInt(s)
if err != nil {
return err
}
paramsDotItemsPerPageVal = c
return nil
}(); err != nil {
return err
}
params.ItemsPerPage.SetTo(paramsDotItemsPerPageVal)
return nil
}(); err != nil {
return params, errors.Wrap(err, "query: itemsPerPage: parse")
}
}
}
return params, nil
}
func decodeReadUsersParams(args [1]string, r *http.Request) (ReadUsersParams, error) {
var (
params ReadUsersParams
)
// Decode path: id.
{
param := args[0]
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
s, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToInt(s)
if err != nil {
return err
}
params.ID = c
return nil
}(); err != nil {
return params, err
}
} else {
return params, errors.New("path: id: not specified")
}
}
return params, nil
}
func decodeUpdateUsersParams(args [1]string, r *http.Request) (UpdateUsersParams, error) {
var (
params UpdateUsersParams
)
// Decode path: id.
{
param := args[0]
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
s, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToInt(s)
if err != nil {
return err
}
params.ID = c
return nil
}(); err != nil {
return params, err
}
} else {
return params, errors.New("path: id: not specified")
}
}
return params, nil
}

View File

@ -1,101 +0,0 @@
// Code generated by ogen, DO NOT EDIT.
package ogent
import (
"bytes"
"context"
"fmt"
"io"
"math"
"math/big"
"math/bits"
"net"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/google/uuid"
"github.com/ogen-go/ogen/conv"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/json"
"github.com/ogen-go/ogen/otelogen"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
// No-op definition for keeping imports.
var (
_ = context.Background()
_ = fmt.Stringer(nil)
_ = strings.Builder{}
_ = errors.Is
_ = sort.Ints
_ = http.MethodGet
_ = io.Copy
_ = json.Marshal
_ = bytes.NewReader
_ = strconv.ParseInt
_ = time.Time{}
_ = conv.ToInt32
_ = uuid.UUID{}
_ = uri.PathEncoder{}
_ = url.URL{}
_ = math.Mod
_ = bits.LeadingZeros64
_ = big.Rat{}
_ = validate.Int{}
_ = ht.NewRequest
_ = net.IP{}
_ = otelogen.Version
_ = attribute.KeyValue{}
_ = trace.TraceIDFromHex
_ = otel.GetTracerProvider
_ = metric.NewNoopMeterProvider
_ = regexp.MustCompile
_ = jx.Null
_ = sync.Pool{}
_ = codes.Unset
)
type DeleteUsersParams struct {
// ID of the Users.
ID int
}
type DrawDoneParams struct {
ID int
}
type DrawStartParams struct {
ID int
}
type ListUsersParams struct {
// What page to render.
Page OptInt
// Item count to render per page.
ItemsPerPage OptInt
}
type ReadUsersParams struct {
// ID of the Users.
ID int
}
type UpdateUsersParams struct {
// ID of the Users.
ID int
}

File diff suppressed because it is too large Load Diff

View File

@ -1,159 +0,0 @@
// Code generated by ogen, DO NOT EDIT.
package ogent
import (
"bytes"
"context"
"fmt"
"io"
"math"
"math/big"
"math/bits"
"net"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/google/uuid"
"github.com/ogen-go/ogen/conv"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/json"
"github.com/ogen-go/ogen/otelogen"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
// No-op definition for keeping imports.
var (
_ = context.Background()
_ = fmt.Stringer(nil)
_ = strings.Builder{}
_ = errors.Is
_ = sort.Ints
_ = http.MethodGet
_ = io.Copy
_ = json.Marshal
_ = bytes.NewReader
_ = strconv.ParseInt
_ = time.Time{}
_ = conv.ToInt32
_ = uuid.UUID{}
_ = uri.PathEncoder{}
_ = url.URL{}
_ = math.Mod
_ = bits.LeadingZeros64
_ = big.Rat{}
_ = validate.Int{}
_ = ht.NewRequest
_ = net.IP{}
_ = otelogen.Version
_ = attribute.KeyValue{}
_ = trace.TraceIDFromHex
_ = otel.GetTracerProvider
_ = metric.NewNoopMeterProvider
_ = regexp.MustCompile
_ = jx.Null
_ = sync.Pool{}
_ = codes.Unset
)
func decodeCreateUsersRequest(r *http.Request, span trace.Span) (req CreateUsersReq, err error) {
switch ct := r.Header.Get("Content-Type"); ct {
case "application/json":
if r.ContentLength == 0 {
return req, validate.ErrBodyRequired
}
var request CreateUsersReq
buf := getBuf()
defer putBuf(buf)
written, err := io.Copy(buf, r.Body)
if err != nil {
return req, err
}
if written == 0 {
return req, validate.ErrBodyRequired
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return req, errors.Wrap(err, "decode CreateUsers:application/json request")
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, errors.Wrap(err, "validate CreateUsers request")
}
return request, nil
default:
return req, validate.InvalidContentType(ct)
}
}
func decodeUpdateUsersRequest(r *http.Request, span trace.Span) (req UpdateUsersReq, err error) {
switch ct := r.Header.Get("Content-Type"); ct {
case "application/json":
if r.ContentLength == 0 {
return req, validate.ErrBodyRequired
}
var request UpdateUsersReq
buf := getBuf()
defer putBuf(buf)
written, err := io.Copy(buf, r.Body)
if err != nil {
return req, err
}
if written == 0 {
return req, validate.ErrBodyRequired
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return req, errors.Wrap(err, "decode UpdateUsers:application/json request")
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, errors.Wrap(err, "validate UpdateUsers request")
}
return request, nil
default:
return req, validate.InvalidContentType(ct)
}
}

View File

@ -1,87 +0,0 @@
// Code generated by ogen, DO NOT EDIT.
package ogent
import (
"bytes"
"context"
"fmt"
"io"
"math"
"math/big"
"math/bits"
"net"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/google/uuid"
"github.com/ogen-go/ogen/conv"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/json"
"github.com/ogen-go/ogen/otelogen"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
// No-op definition for keeping imports.
var (
_ = context.Background()
_ = fmt.Stringer(nil)
_ = strings.Builder{}
_ = errors.Is
_ = sort.Ints
_ = http.MethodGet
_ = io.Copy
_ = json.Marshal
_ = bytes.NewReader
_ = strconv.ParseInt
_ = time.Time{}
_ = conv.ToInt32
_ = uuid.UUID{}
_ = uri.PathEncoder{}
_ = url.URL{}
_ = math.Mod
_ = bits.LeadingZeros64
_ = big.Rat{}
_ = validate.Int{}
_ = ht.NewRequest
_ = net.IP{}
_ = otelogen.Version
_ = attribute.KeyValue{}
_ = trace.TraceIDFromHex
_ = otel.GetTracerProvider
_ = metric.NewNoopMeterProvider
_ = regexp.MustCompile
_ = jx.Null
_ = sync.Pool{}
_ = codes.Unset
)
func encodeCreateUsersRequestJSON(req CreateUsersReq, span trace.Span) (data *jx.Encoder, err error) {
e := jx.GetEncoder()
req.Encode(e)
return e, nil
}
func encodeUpdateUsersRequestJSON(req UpdateUsersReq, span trace.Span) (data *jx.Encoder, err error) {
e := jx.GetEncoder()
req.Encode(e)
return e, nil
}

View File

@ -0,0 +1,394 @@
// Code generated by ogen, DO NOT EDIT.
package ogent
import (
"io"
"mime"
"net/http"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"go.uber.org/multierr"
"github.com/ogen-go/ogen/ogenerrors"
"github.com/ogen-go/ogen/validate"
)
func (s *Server) decodeCreateCardRequest(r *http.Request) (
req *CreateCardReq,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = multierr.Append(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = multierr.Append(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
if err != nil {
return req, close, err
}
if len(buf) == 0 {
return req, close, validate.ErrBodyRequired
}
d := jx.DecodeBytes(buf)
var request CreateCardReq
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, close, err
}
return &request, close, nil
default:
return req, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeCreateGroupRequest(r *http.Request) (
req *CreateGroupReq,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = multierr.Append(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = multierr.Append(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
if err != nil {
return req, close, err
}
if len(buf) == 0 {
return req, close, validate.ErrBodyRequired
}
d := jx.DecodeBytes(buf)
var request CreateGroupReq
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, close, err
}
return &request, close, nil
default:
return req, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeCreateUserRequest(r *http.Request) (
req *CreateUserReq,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = multierr.Append(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = multierr.Append(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
if err != nil {
return req, close, err
}
if len(buf) == 0 {
return req, close, validate.ErrBodyRequired
}
d := jx.DecodeBytes(buf)
var request CreateUserReq
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, close, err
}
return &request, close, nil
default:
return req, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeUpdateCardRequest(r *http.Request) (
req *UpdateCardReq,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = multierr.Append(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = multierr.Append(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
if err != nil {
return req, close, err
}
if len(buf) == 0 {
return req, close, validate.ErrBodyRequired
}
d := jx.DecodeBytes(buf)
var request UpdateCardReq
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, close, err
}
return &request, close, nil
default:
return req, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeUpdateGroupRequest(r *http.Request) (
req *UpdateGroupReq,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = multierr.Append(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = multierr.Append(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
if err != nil {
return req, close, err
}
if len(buf) == 0 {
return req, close, validate.ErrBodyRequired
}
d := jx.DecodeBytes(buf)
var request UpdateGroupReq
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, close, err
}
return &request, close, nil
default:
return req, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeUpdateUserRequest(r *http.Request) (
req *UpdateUserReq,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = multierr.Append(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = multierr.Append(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
if err != nil {
return req, close, err
}
if len(buf) == 0 {
return req, close, validate.ErrBodyRequired
}
d := jx.DecodeBytes(buf)
var request UpdateUserReq
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, close, err
}
return &request, close, nil
default:
return req, close, validate.InvalidContentType(ct)
}
}

View File

@ -0,0 +1,96 @@
// Code generated by ogen, DO NOT EDIT.
package ogent
import (
"bytes"
"net/http"
"github.com/go-faster/jx"
ht "github.com/ogen-go/ogen/http"
)
func encodeCreateCardRequest(
req *CreateCardReq,
r *http.Request,
) error {
const contentType = "application/json"
e := jx.GetEncoder()
{
req.Encode(e)
}
encoded := e.Bytes()
ht.SetBody(r, bytes.NewReader(encoded), contentType)
return nil
}
func encodeCreateGroupRequest(
req *CreateGroupReq,
r *http.Request,
) error {
const contentType = "application/json"
e := jx.GetEncoder()
{
req.Encode(e)
}
encoded := e.Bytes()
ht.SetBody(r, bytes.NewReader(encoded), contentType)
return nil
}
func encodeCreateUserRequest(
req *CreateUserReq,
r *http.Request,
) error {
const contentType = "application/json"
e := jx.GetEncoder()
{
req.Encode(e)
}
encoded := e.Bytes()
ht.SetBody(r, bytes.NewReader(encoded), contentType)
return nil
}
func encodeUpdateCardRequest(
req *UpdateCardReq,
r *http.Request,
) error {
const contentType = "application/json"
e := jx.GetEncoder()
{
req.Encode(e)
}
encoded := e.Bytes()
ht.SetBody(r, bytes.NewReader(encoded), contentType)
return nil
}
func encodeUpdateGroupRequest(
req *UpdateGroupReq,
r *http.Request,
) error {
const contentType = "application/json"
e := jx.GetEncoder()
{
req.Encode(e)
}
encoded := e.Bytes()
ht.SetBody(r, bytes.NewReader(encoded), contentType)
return nil
}
func encodeUpdateUserRequest(
req *UpdateUserReq,
r *http.Request,
) error {
const contentType = "application/json"
e := jx.GetEncoder()
{
req.Encode(e)
}
encoded := e.Bytes()
ht.SetBody(r, bytes.NewReader(encoded), contentType)
return nil
}

View File

@ -1,747 +0,0 @@
// Code generated by ogen, DO NOT EDIT.
package ogent
import (
"bytes"
"context"
"fmt"
"io"
"math"
"math/big"
"math/bits"
"net"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/google/uuid"
"github.com/ogen-go/ogen/conv"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/json"
"github.com/ogen-go/ogen/otelogen"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
// No-op definition for keeping imports.
var (
_ = context.Background()
_ = fmt.Stringer(nil)
_ = strings.Builder{}
_ = errors.Is
_ = sort.Ints
_ = http.MethodGet
_ = io.Copy
_ = json.Marshal
_ = bytes.NewReader
_ = strconv.ParseInt
_ = time.Time{}
_ = conv.ToInt32
_ = uuid.UUID{}
_ = uri.PathEncoder{}
_ = url.URL{}
_ = math.Mod
_ = bits.LeadingZeros64
_ = big.Rat{}
_ = validate.Int{}
_ = ht.NewRequest
_ = net.IP{}
_ = otelogen.Version
_ = attribute.KeyValue{}
_ = trace.TraceIDFromHex
_ = otel.GetTracerProvider
_ = metric.NewNoopMeterProvider
_ = regexp.MustCompile
_ = jx.Null
_ = sync.Pool{}
_ = codes.Unset
)
func decodeCreateUsersResponse(resp *http.Response, span trace.Span) (res CreateUsersRes, err error) {
switch resp.StatusCode {
case 200:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response UsersCreate
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 400:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R400
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 409:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R409
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 500:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R500
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
default:
return res, validate.UnexpectedStatusCode(resp.StatusCode)
}
}
func decodeDeleteUsersResponse(resp *http.Response, span trace.Span) (res DeleteUsersRes, err error) {
switch resp.StatusCode {
case 204:
return &DeleteUsersNoContent{}, nil
case 400:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R400
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 404:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R404
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 409:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R409
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 500:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R500
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
default:
return res, validate.UnexpectedStatusCode(resp.StatusCode)
}
}
func decodeDrawDoneResponse(resp *http.Response, span trace.Span) (res DrawDoneNoContent, err error) {
switch resp.StatusCode {
case 204:
return DrawDoneNoContent{}, nil
default:
return res, validate.UnexpectedStatusCode(resp.StatusCode)
}
}
func decodeDrawStartResponse(resp *http.Response, span trace.Span) (res DrawStartNoContent, err error) {
switch resp.StatusCode {
case 204:
return DrawStartNoContent{}, nil
default:
return res, validate.UnexpectedStatusCode(resp.StatusCode)
}
}
func decodeListUsersResponse(resp *http.Response, span trace.Span) (res ListUsersRes, err error) {
switch resp.StatusCode {
case 200:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response ListUsersOKApplicationJSON
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 400:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R400
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 404:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R404
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 409:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R409
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 500:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R500
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
default:
return res, validate.UnexpectedStatusCode(resp.StatusCode)
}
}
func decodeReadUsersResponse(resp *http.Response, span trace.Span) (res ReadUsersRes, err error) {
switch resp.StatusCode {
case 200:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response UsersRead
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 400:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R400
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 404:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R404
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 409:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R409
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 500:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R500
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
default:
return res, validate.UnexpectedStatusCode(resp.StatusCode)
}
}
func decodeUpdateUsersResponse(resp *http.Response, span trace.Span) (res UpdateUsersRes, err error) {
switch resp.StatusCode {
case 200:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response UsersUpdate
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 400:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R400
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 404:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R404
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 409:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R409
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
case 500:
switch ct := resp.Header.Get("Content-Type"); ct {
case "application/json":
buf := getBuf()
defer putBuf(buf)
if _, err := io.Copy(buf, resp.Body); err != nil {
return res, err
}
d := jx.GetDecoder()
defer jx.PutDecoder(d)
d.ResetBytes(buf.Bytes())
var response R500
if err := func() error {
if err := response.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return res, err
}
return &response, nil
default:
return res, validate.InvalidContentType(ct)
}
default:
return res, validate.UnexpectedStatusCode(resp.StatusCode)
}
}

View File

@ -1,395 +0,0 @@
// Code generated by ogen, DO NOT EDIT.
package ogent
import (
"bytes"
"context"
"fmt"
"io"
"math"
"math/big"
"math/bits"
"net"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/google/uuid"
"github.com/ogen-go/ogen/conv"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/json"
"github.com/ogen-go/ogen/otelogen"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
// No-op definition for keeping imports.
var (
_ = context.Background()
_ = fmt.Stringer(nil)
_ = strings.Builder{}
_ = errors.Is
_ = sort.Ints
_ = http.MethodGet
_ = io.Copy
_ = json.Marshal
_ = bytes.NewReader
_ = strconv.ParseInt
_ = time.Time{}
_ = conv.ToInt32
_ = uuid.UUID{}
_ = uri.PathEncoder{}
_ = url.URL{}
_ = math.Mod
_ = bits.LeadingZeros64
_ = big.Rat{}
_ = validate.Int{}
_ = ht.NewRequest
_ = net.IP{}
_ = otelogen.Version
_ = attribute.KeyValue{}
_ = trace.TraceIDFromHex
_ = otel.GetTracerProvider
_ = metric.NewNoopMeterProvider
_ = regexp.MustCompile
_ = jx.Null
_ = sync.Pool{}
_ = codes.Unset
)
func encodeCreateUsersResponse(response CreateUsersRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *UsersCreate:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R400:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(400)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R409:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(409)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R500:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(500)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("/users"+`: unexpected response type: %T`, response)
}
}
func encodeDeleteUsersResponse(response DeleteUsersRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *DeleteUsersNoContent:
w.WriteHeader(204)
return nil
case *R400:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(400)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R404:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(404)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R409:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(409)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R500:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(500)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("/users/{id}"+`: unexpected response type: %T`, response)
}
}
func encodeDrawDoneResponse(response DrawDoneNoContent, w http.ResponseWriter, span trace.Span) error {
w.WriteHeader(204)
return nil
}
func encodeDrawStartResponse(response DrawStartNoContent, w http.ResponseWriter, span trace.Span) error {
w.WriteHeader(204)
return nil
}
func encodeListUsersResponse(response ListUsersRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *ListUsersOKApplicationJSON:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R400:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(400)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R404:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(404)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R409:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(409)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R500:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(500)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("/users"+`: unexpected response type: %T`, response)
}
}
func encodeReadUsersResponse(response ReadUsersRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *UsersRead:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R400:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(400)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R404:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(404)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R409:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(409)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R500:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(500)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("/users/{id}"+`: unexpected response type: %T`, response)
}
}
func encodeUpdateUsersResponse(response UpdateUsersRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *UsersUpdate:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R400:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(400)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R404:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(404)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R409:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(409)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *R500:
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(500)
e := jx.GetEncoder()
defer jx.PutEncoder(e)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("/users/{id}"+`: unexpected response type: %T`, response)
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -3,128 +3,72 @@
package ogent
import (
"bytes"
"context"
"fmt"
"io"
"math"
"math/big"
"math/bits"
"net"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/google/uuid"
"github.com/ogen-go/ogen/conv"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/json"
"github.com/ogen-go/ogen/otelogen"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
// No-op definition for keeping imports.
var (
_ = context.Background()
_ = fmt.Stringer(nil)
_ = strings.Builder{}
_ = errors.Is
_ = sort.Ints
_ = http.MethodGet
_ = io.Copy
_ = json.Marshal
_ = bytes.NewReader
_ = strconv.ParseInt
_ = time.Time{}
_ = conv.ToInt32
_ = uuid.UUID{}
_ = uri.PathEncoder{}
_ = url.URL{}
_ = math.Mod
_ = bits.LeadingZeros64
_ = big.Rat{}
_ = validate.Int{}
_ = ht.NewRequest
_ = net.IP{}
_ = otelogen.Version
_ = attribute.KeyValue{}
_ = trace.TraceIDFromHex
_ = otel.GetTracerProvider
_ = metric.NewNoopMeterProvider
_ = regexp.MustCompile
_ = jx.Null
_ = sync.Pool{}
_ = codes.Unset
)
func (s *Server) notFound(w http.ResponseWriter, r *http.Request) {
s.cfg.NotFound(w, r)
}
// ServeHTTP serves http request as defined by OpenAPI v3 specification,
// calling handler that matches the path or returning not found error.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
elem := r.URL.Path
if rawPath := r.URL.RawPath; rawPath != "" {
if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
elem = normalized
}
}
if prefix := s.cfg.Prefix; len(prefix) > 0 {
if strings.HasPrefix(elem, prefix) {
// Cut prefix from the path.
elem = strings.TrimPrefix(elem, prefix)
} else {
// Prefix doesn't match.
s.notFound(w, r)
return
}
}
if len(elem) == 0 {
s.notFound(w, r)
return
}
args := [1]string{}
// Static code generated router with unwrapped path search.
switch {
default:
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
break
}
switch elem[0] {
case 'c': // Prefix: "cards"
if l := len("cards"); len(elem) >= l && elem[0:l] == "cards" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch r.Method {
case "DELETE":
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/users/"
if l := len("/users/"); len(elem) >= l && elem[0:l] == "/users/" {
elem = elem[l:]
} else {
break
}
// Param: "id"
// Leaf parameter
args[0] = elem
elem = ""
if len(elem) == 0 {
// Leaf: DeleteUsers
s.handleDeleteUsersRequest([1]string{
args[0],
}, w, r)
return
}
}
case "GET":
if len(elem) == 0 {
break
s.handleListCardRequest([0]string{}, w, r)
case "POST":
s.handleCreateCardRequest([0]string{}, w, r)
default:
s.notAllowed(w, r, "GET,POST")
}
switch elem[0] {
case '/': // Prefix: "/users"
if l := len("/users"); len(elem) >= l && elem[0:l] == "/users" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
s.handleListUsersRequest([0]string{}, w, r)
return
}
@ -137,27 +81,111 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
// Param: "id"
// Leaf parameter
args[0] = elem
elem = ""
// Match until "/"
idx := strings.IndexByte(elem, '/')
if idx < 0 {
idx = len(elem)
}
args[0] = elem[:idx]
elem = elem[idx:]
if len(elem) == 0 {
// Leaf: ReadUsers
s.handleReadUsersRequest([1]string{
switch r.Method {
case "DELETE":
s.handleDeleteCardRequest([1]string{
args[0],
}, w, r)
case "GET":
s.handleReadCardRequest([1]string{
args[0],
}, w, r)
case "PATCH":
s.handleUpdateCardRequest([1]string{
args[0],
}, w, r)
default:
s.notAllowed(w, r, "DELETE,GET,PATCH")
}
return
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
break
}
switch elem[0] {
case 'd': // Prefix: "d"
if l := len("d"); len(elem) >= l && elem[0:l] == "d" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "PUT":
s.handleDrawDoneRequest([1]string{
args[0],
}, w, r)
default:
s.notAllowed(w, r, "PUT")
}
return
}
case 'o': // Prefix: "owner"
if l := len("owner"); len(elem) >= l && elem[0:l] == "owner" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleReadCardOwnerRequest([1]string{
args[0],
}, w, r)
default:
s.notAllowed(w, r, "GET")
}
return
}
}
}
case "PATCH":
if len(elem) == 0 {
}
case 'g': // Prefix: "groups"
if l := len("groups"); len(elem) >= l && elem[0:l] == "groups" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch r.Method {
case "GET":
s.handleListGroupRequest([0]string{}, w, r)
case "POST":
s.handleCreateGroupRequest([0]string{}, w, r)
default:
s.notAllowed(w, r, "GET,POST")
}
return
}
switch elem[0] {
case '/': // Prefix: "/users/"
if l := len("/users/"); len(elem) >= l && elem[0:l] == "/users/" {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
@ -173,9 +201,121 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
elem = elem[idx:]
if len(elem) == 0 {
s.handleUpdateUsersRequest([1]string{
switch r.Method {
case "DELETE":
s.handleDeleteGroupRequest([1]string{
args[0],
}, w, r)
case "GET":
s.handleReadGroupRequest([1]string{
args[0],
}, w, r)
case "PATCH":
s.handleUpdateGroupRequest([1]string{
args[0],
}, w, r)
default:
s.notAllowed(w, r, "DELETE,GET,PATCH")
}
return
}
switch elem[0] {
case '/': // Prefix: "/users"
if l := len("/users"); len(elem) >= l && elem[0:l] == "/users" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleListGroupUsersRequest([1]string{
args[0],
}, w, r)
default:
s.notAllowed(w, r, "GET")
}
return
}
}
}
case 'u': // Prefix: "users"
if l := len("users"); len(elem) >= l && elem[0:l] == "users" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch r.Method {
case "GET":
s.handleListUserRequest([0]string{}, w, r)
case "POST":
s.handleCreateUserRequest([0]string{}, w, r)
default:
s.notAllowed(w, r, "GET,POST")
}
return
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
// Param: "id"
// Match until "/"
idx := strings.IndexByte(elem, '/')
if idx < 0 {
idx = len(elem)
}
args[0] = elem[:idx]
elem = elem[idx:]
if len(elem) == 0 {
switch r.Method {
case "DELETE":
s.handleDeleteUserRequest([1]string{
args[0],
}, w, r)
case "GET":
s.handleReadUserRequest([1]string{
args[0],
}, w, r)
case "PATCH":
s.handleUpdateUserRequest([1]string{
args[0],
}, w, r)
default:
s.notAllowed(w, r, "DELETE,GET,PATCH")
}
return
}
switch elem[0] {
case '/': // Prefix: "/card"
if l := len("/card"); len(elem) >= l && elem[0:l] == "/card" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch r.Method {
case "GET":
s.handleListUserCardRequest([1]string{
args[0],
}, w, r)
default:
s.notAllowed(w, r, "GET")
}
return
}
@ -188,73 +328,20 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
if len(elem) == 0 {
// Leaf: DrawStart
// Leaf node.
switch r.Method {
case "PATCH":
s.handleDrawStartRequest([1]string{
args[0],
}, w, r)
default:
s.notAllowed(w, r, "PATCH")
}
return
}
}
}
case "POST":
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/users"
if l := len("/users"); len(elem) >= l && elem[0:l] == "/users" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf: CreateUsers
s.handleCreateUsersRequest([0]string{}, w, r)
return
}
}
case "PUT":
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/users/"
if l := len("/users/"); len(elem) >= l && elem[0:l] == "/users/" {
elem = elem[l:]
} else {
break
}
// Param: "id"
// Match until "/"
idx := strings.IndexByte(elem, '/')
if idx < 0 {
idx = len(elem)
}
args[0] = elem[:idx]
elem = elem[idx:]
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/d"
if l := len("/d"); len(elem) >= l && elem[0:l] == "/d" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf: DrawDone
s.handleDrawDoneRequest([1]string{
args[0],
}, w, r)
return
}
}
}
@ -265,13 +352,27 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Route is route object.
type Route struct {
name string
operationID string
pathPattern string
count int
args [1]string
}
// Name returns ogen operation name.
//
// It is guaranteed to be unique and not empty.
func (r Route) Name() string {
return r.name
}
// OperationID returns OpenAPI operationId.
func (r Route) OperationID() string {
return r.name
return r.operationID
}
// PathPattern returns OpenAPI path.
func (r Route) PathPattern() string {
return r.pathPattern
}
// Args returns parsed arguments.
@ -280,60 +381,75 @@ func (r Route) Args() []string {
}
// FindRoute finds Route for given method and path.
func (s *Server) FindRoute(method, path string) (r Route, _ bool) {
//
// Note: this method does not unescape path or handle reserved characters in path properly. Use FindPath instead.
func (s *Server) FindRoute(method, path string) (Route, bool) {
return s.FindPath(method, &url.URL{Path: path})
}
// FindPath finds Route for given method and URL.
func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
var (
args = [1]string{}
elem = path
elem = u.Path
args = r.args
)
r.args = args
if elem == "" {
return r, false
if rawPath := u.RawPath; rawPath != "" {
if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
elem = normalized
}
defer func() {
for i, arg := range r.args[:r.count] {
if unescaped, err := url.PathUnescape(arg); err == nil {
r.args[i] = unescaped
}
}
}()
}
// Static code generated router with unwrapped path search.
switch {
default:
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
break
}
switch elem[0] {
case 'c': // Prefix: "cards"
if l := len("cards"); len(elem) >= l && elem[0:l] == "cards" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch method {
case "DELETE":
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/users/"
if l := len("/users/"); len(elem) >= l && elem[0:l] == "/users/" {
elem = elem[l:]
} else {
break
}
// Param: "id"
// Leaf parameter
args[0] = elem
elem = ""
if len(elem) == 0 {
// Leaf: DeleteUsers
r.name = "DeleteUsers"
r.args = args
r.count = 1
return r, true
}
}
case "GET":
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/users"
if l := len("/users"); len(elem) >= l && elem[0:l] == "/users" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
r.name = "ListUsers"
r.name = "ListCard"
r.operationID = "listCard"
r.pathPattern = "/cards"
r.args = args
r.count = 0
return r, true
case "POST":
r.name = "CreateCard"
r.operationID = "createCard"
r.pathPattern = "/cards"
r.args = args
r.count = 0
return r, true
default:
return
}
}
switch elem[0] {
case '/': // Prefix: "/"
@ -344,26 +460,128 @@ func (s *Server) FindRoute(method, path string) (r Route, _ bool) {
}
// Param: "id"
// Leaf parameter
args[0] = elem
elem = ""
// Match until "/"
idx := strings.IndexByte(elem, '/')
if idx < 0 {
idx = len(elem)
}
args[0] = elem[:idx]
elem = elem[idx:]
if len(elem) == 0 {
// Leaf: ReadUsers
r.name = "ReadUsers"
switch method {
case "DELETE":
r.name = "DeleteCard"
r.operationID = "deleteCard"
r.pathPattern = "/cards/{id}"
r.args = args
r.count = 1
return r, true
case "GET":
r.name = "ReadCard"
r.operationID = "readCard"
r.pathPattern = "/cards/{id}"
r.args = args
r.count = 1
return r, true
}
}
}
case "PATCH":
r.name = "UpdateCard"
r.operationID = "updateCard"
r.pathPattern = "/cards/{id}"
r.args = args
r.count = 1
return r, true
default:
return
}
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/users/"
if l := len("/users/"); len(elem) >= l && elem[0:l] == "/users/" {
case 'd': // Prefix: "d"
if l := len("d"); len(elem) >= l && elem[0:l] == "d" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch method {
case "PUT":
// Leaf: DrawDone
r.name = "DrawDone"
r.operationID = "drawDone"
r.pathPattern = "/cards/{id}/d"
r.args = args
r.count = 1
return r, true
default:
return
}
}
case 'o': // Prefix: "owner"
if l := len("owner"); len(elem) >= l && elem[0:l] == "owner" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch method {
case "GET":
// Leaf: ReadCardOwner
r.name = "ReadCardOwner"
r.operationID = "readCardOwner"
r.pathPattern = "/cards/{id}/owner"
r.args = args
r.count = 1
return r, true
default:
return
}
}
}
}
}
case 'g': // Prefix: "groups"
if l := len("groups"); len(elem) >= l && elem[0:l] == "groups" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch method {
case "GET":
r.name = "ListGroup"
r.operationID = "listGroup"
r.pathPattern = "/groups"
r.args = args
r.count = 0
return r, true
case "POST":
r.name = "CreateGroup"
r.operationID = "createGroup"
r.pathPattern = "/groups"
r.args = args
r.count = 0
return r, true
default:
return
}
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
@ -379,32 +597,32 @@ func (s *Server) FindRoute(method, path string) (r Route, _ bool) {
elem = elem[idx:]
if len(elem) == 0 {
r.name = "UpdateUsers"
switch method {
case "DELETE":
r.name = "DeleteGroup"
r.operationID = "deleteGroup"
r.pathPattern = "/groups/{id}"
r.args = args
r.count = 1
return r, true
}
switch elem[0] {
case '/': // Prefix: "/start"
if l := len("/start"); len(elem) >= l && elem[0:l] == "/start" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf: DrawStart
r.name = "DrawStart"
case "GET":
r.name = "ReadGroup"
r.operationID = "readGroup"
r.pathPattern = "/groups/{id}"
r.args = args
r.count = 1
return r, true
case "PATCH":
r.name = "UpdateGroup"
r.operationID = "updateGroup"
r.pathPattern = "/groups/{id}"
r.args = args
r.count = 1
return r, true
default:
return
}
}
}
case "POST":
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/users"
if l := len("/users"); len(elem) >= l && elem[0:l] == "/users" {
@ -414,20 +632,51 @@ func (s *Server) FindRoute(method, path string) (r Route, _ bool) {
}
if len(elem) == 0 {
// Leaf: CreateUsers
r.name = "CreateUsers"
switch method {
case "GET":
// Leaf: ListGroupUsers
r.name = "ListGroupUsers"
r.operationID = "listGroupUsers"
r.pathPattern = "/groups/{id}/users"
r.args = args
r.count = 1
return r, true
default:
return
}
}
}
}
case 'u': // Prefix: "users"
if l := len("users"); len(elem) >= l && elem[0:l] == "users" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch method {
case "GET":
r.name = "ListUser"
r.operationID = "listUser"
r.pathPattern = "/users"
r.args = args
r.count = 0
return r, true
case "POST":
r.name = "CreateUser"
r.operationID = "createUser"
r.pathPattern = "/users"
r.args = args
r.count = 0
return r, true
default:
return
}
}
case "PUT":
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/users/"
if l := len("/users/"); len(elem) >= l && elem[0:l] == "/users/" {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
@ -443,22 +692,77 @@ func (s *Server) FindRoute(method, path string) (r Route, _ bool) {
elem = elem[idx:]
if len(elem) == 0 {
break
switch method {
case "DELETE":
r.name = "DeleteUser"
r.operationID = "deleteUser"
r.pathPattern = "/users/{id}"
r.args = args
r.count = 1
return r, true
case "GET":
r.name = "ReadUser"
r.operationID = "readUser"
r.pathPattern = "/users/{id}"
r.args = args
r.count = 1
return r, true
case "PATCH":
r.name = "UpdateUser"
r.operationID = "updateUser"
r.pathPattern = "/users/{id}"
r.args = args
r.count = 1
return r, true
default:
return
}
}
switch elem[0] {
case '/': // Prefix: "/d"
if l := len("/d"); len(elem) >= l && elem[0:l] == "/d" {
case '/': // Prefix: "/card"
if l := len("/card"); len(elem) >= l && elem[0:l] == "/card" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf: DrawDone
r.name = "DrawDone"
switch method {
case "GET":
r.name = "ListUserCard"
r.operationID = "listUserCard"
r.pathPattern = "/users/{id}/card"
r.args = args
r.count = 1
return r, true
default:
return
}
}
switch elem[0] {
case '/': // Prefix: "/start"
if l := len("/start"); len(elem) >= l && elem[0:l] == "/start" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch method {
case "PATCH":
// Leaf: DrawStart
r.name = "DrawStart"
r.operationID = "drawStart"
r.pathPattern = "/users/{id}/card/start"
r.args = args
r.count = 1
return r, true
default:
return
}
}
}
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,71 +0,0 @@
// Code generated by ogen, DO NOT EDIT.
package ogent
import (
"bytes"
"context"
"fmt"
"io"
"math"
"math/big"
"math/bits"
"net"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/google/uuid"
"github.com/ogen-go/ogen/conv"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/json"
"github.com/ogen-go/ogen/otelogen"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
// No-op definition for keeping imports.
var (
_ = context.Background()
_ = fmt.Stringer(nil)
_ = strings.Builder{}
_ = errors.Is
_ = sort.Ints
_ = http.MethodGet
_ = io.Copy
_ = json.Marshal
_ = bytes.NewReader
_ = strconv.ParseInt
_ = time.Time{}
_ = conv.ToInt32
_ = uuid.UUID{}
_ = uri.PathEncoder{}
_ = url.URL{}
_ = math.Mod
_ = bits.LeadingZeros64
_ = big.Rat{}
_ = validate.Int{}
_ = ht.NewRequest
_ = net.IP{}
_ = otelogen.Version
_ = attribute.KeyValue{}
_ = trace.TraceIDFromHex
_ = otel.GetTracerProvider
_ = metric.NewNoopMeterProvider
_ = regexp.MustCompile
_ = jx.Null
_ = sync.Pool{}
_ = codes.Unset
)

View File

@ -3,140 +3,148 @@
package ogent
import (
"bytes"
"context"
"fmt"
"io"
"math"
"math/big"
"math/bits"
"net"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/google/uuid"
"github.com/ogen-go/ogen/conv"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/json"
"github.com/ogen-go/ogen/otelogen"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
// No-op definition for keeping imports.
var (
_ = context.Background()
_ = fmt.Stringer(nil)
_ = strings.Builder{}
_ = errors.Is
_ = sort.Ints
_ = http.MethodGet
_ = io.Copy
_ = json.Marshal
_ = bytes.NewReader
_ = strconv.ParseInt
_ = time.Time{}
_ = conv.ToInt32
_ = uuid.UUID{}
_ = uri.PathEncoder{}
_ = url.URL{}
_ = math.Mod
_ = bits.LeadingZeros64
_ = big.Rat{}
_ = validate.Int{}
_ = ht.NewRequest
_ = net.IP{}
_ = otelogen.Version
_ = attribute.KeyValue{}
_ = trace.TraceIDFromHex
_ = otel.GetTracerProvider
_ = metric.NewNoopMeterProvider
_ = regexp.MustCompile
_ = jx.Null
_ = sync.Pool{}
_ = codes.Unset
)
// Handler handles operations described by OpenAPI v3 specification.
type Handler interface {
// CreateUsers implements createUsers operation.
// CreateCard implements createCard operation.
//
// Creates a new Users and persists it to storage.
// Creates a new Card and persists it to storage.
//
// POST /cards
CreateCard(ctx context.Context, req *CreateCardReq) (CreateCardRes, error)
// CreateGroup implements createGroup operation.
//
// Creates a new Group and persists it to storage.
//
// POST /groups
CreateGroup(ctx context.Context, req *CreateGroupReq) (CreateGroupRes, error)
// CreateUser implements createUser operation.
//
// Creates a new User and persists it to storage.
//
// POST /users
CreateUsers(ctx context.Context, req CreateUsersReq) (CreateUsersRes, error)
// DeleteUsers implements deleteUsers operation.
CreateUser(ctx context.Context, req *CreateUserReq) (CreateUserRes, error)
// DeleteCard implements deleteCard operation.
//
// Deletes the Users with the requested ID.
// Deletes the Card with the requested ID.
//
// DELETE /cards/{id}
DeleteCard(ctx context.Context, params DeleteCardParams) (DeleteCardRes, error)
// DeleteGroup implements deleteGroup operation.
//
// Deletes the Group with the requested ID.
//
// DELETE /groups/{id}
DeleteGroup(ctx context.Context, params DeleteGroupParams) (DeleteGroupRes, error)
// DeleteUser implements deleteUser operation.
//
// Deletes the User with the requested ID.
//
// DELETE /users/{id}
DeleteUsers(ctx context.Context, params DeleteUsersParams) (DeleteUsersRes, error)
DeleteUser(ctx context.Context, params DeleteUserParams) (DeleteUserRes, error)
// DrawDone implements drawDone operation.
//
// PUT /users/{id}/d
DrawDone(ctx context.Context, params DrawDoneParams) (DrawDoneNoContent, error)
// Draws a card item as done.
//
// PUT /cards/{id}/d
DrawDone(ctx context.Context, params DrawDoneParams) error
// DrawStart implements drawStart operation.
//
// PATCH /users/{id}/start
DrawStart(ctx context.Context, params DrawStartParams) (DrawStartNoContent, error)
// ListUsers implements listUsers operation.
// Draws a card item as done.
//
// PATCH /users/{id}/card/start
DrawStart(ctx context.Context, params DrawStartParams) error
// ListCard implements listCard operation.
//
// List Cards.
//
// GET /cards
ListCard(ctx context.Context, params ListCardParams) (ListCardRes, error)
// ListGroup implements listGroup operation.
//
// List Groups.
//
// GET /groups
ListGroup(ctx context.Context, params ListGroupParams) (ListGroupRes, error)
// ListGroupUsers implements listGroupUsers operation.
//
// List attached Users.
//
// GET /groups/{id}/users
ListGroupUsers(ctx context.Context, params ListGroupUsersParams) (ListGroupUsersRes, error)
// ListUser implements listUser operation.
//
// List Users.
//
// GET /users
ListUsers(ctx context.Context, params ListUsersParams) (ListUsersRes, error)
// ReadUsers implements readUsers operation.
ListUser(ctx context.Context, params ListUserParams) (ListUserRes, error)
// ListUserCard implements listUserCard operation.
//
// Finds the Users with the requested ID and returns it.
// List attached Cards.
//
// GET /users/{id}/card
ListUserCard(ctx context.Context, params ListUserCardParams) (ListUserCardRes, error)
// ReadCard implements readCard operation.
//
// Finds the Card with the requested ID and returns it.
//
// GET /cards/{id}
ReadCard(ctx context.Context, params ReadCardParams) (ReadCardRes, error)
// ReadCardOwner implements readCardOwner operation.
//
// Find the attached User of the Card with the given ID.
//
// GET /cards/{id}/owner
ReadCardOwner(ctx context.Context, params ReadCardOwnerParams) (ReadCardOwnerRes, error)
// ReadGroup implements readGroup operation.
//
// Finds the Group with the requested ID and returns it.
//
// GET /groups/{id}
ReadGroup(ctx context.Context, params ReadGroupParams) (ReadGroupRes, error)
// ReadUser implements readUser operation.
//
// Finds the User with the requested ID and returns it.
//
// GET /users/{id}
ReadUsers(ctx context.Context, params ReadUsersParams) (ReadUsersRes, error)
// UpdateUsers implements updateUsers operation.
ReadUser(ctx context.Context, params ReadUserParams) (ReadUserRes, error)
// UpdateCard implements updateCard operation.
//
// Updates a Users and persists changes to storage.
// Updates a Card and persists changes to storage.
//
// PATCH /cards/{id}
UpdateCard(ctx context.Context, req *UpdateCardReq, params UpdateCardParams) (UpdateCardRes, error)
// UpdateGroup implements updateGroup operation.
//
// Updates a Group and persists changes to storage.
//
// PATCH /groups/{id}
UpdateGroup(ctx context.Context, req *UpdateGroupReq, params UpdateGroupParams) (UpdateGroupRes, error)
// UpdateUser implements updateUser operation.
//
// Updates a User and persists changes to storage.
//
// PATCH /users/{id}
UpdateUsers(ctx context.Context, req UpdateUsersReq, params UpdateUsersParams) (UpdateUsersRes, error)
UpdateUser(ctx context.Context, req *UpdateUserReq, params UpdateUserParams) (UpdateUserRes, error)
}
// Server implements http server based on OpenAPI v3 specification and
// calls Handler to handle requests.
type Server struct {
h Handler
cfg config
requests metric.Int64Counter
errors metric.Int64Counter
duration metric.Int64Histogram
baseServer
}
func NewServer(h Handler, opts ...Option) (*Server, error) {
s := &Server{
// NewServer creates new Server.
func NewServer(h Handler, opts ...ServerOption) (*Server, error) {
s, err := newServerConfig(opts...).baseServer()
if err != nil {
return nil, err
}
return &Server{
h: h,
cfg: newConfig(opts...),
}
var err error
if s.requests, err = s.cfg.Meter.NewInt64Counter(otelogen.ServerRequestCount); err != nil {
return nil, err
}
if s.errors, err = s.cfg.Meter.NewInt64Counter(otelogen.ServerErrorsCount); err != nil {
return nil, err
}
if s.duration, err = s.cfg.Meter.NewInt64Histogram(otelogen.ServerDuration); err != nil {
return nil, err
}
return s, nil
baseServer: s,
}, nil
}

View File

@ -3,133 +3,192 @@
package ogent
import (
"bytes"
"context"
"fmt"
"io"
"math"
"math/big"
"math/bits"
"net"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/google/uuid"
"github.com/ogen-go/ogen/conv"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/json"
"github.com/ogen-go/ogen/otelogen"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
// No-op definition for keeping imports.
var (
_ = context.Background()
_ = fmt.Stringer(nil)
_ = strings.Builder{}
_ = errors.Is
_ = sort.Ints
_ = http.MethodGet
_ = io.Copy
_ = json.Marshal
_ = bytes.NewReader
_ = strconv.ParseInt
_ = time.Time{}
_ = conv.ToInt32
_ = uuid.UUID{}
_ = uri.PathEncoder{}
_ = url.URL{}
_ = math.Mod
_ = bits.LeadingZeros64
_ = big.Rat{}
_ = validate.Int{}
_ = ht.NewRequest
_ = net.IP{}
_ = otelogen.Version
_ = attribute.KeyValue{}
_ = trace.TraceIDFromHex
_ = otel.GetTracerProvider
_ = metric.NewNoopMeterProvider
_ = regexp.MustCompile
_ = jx.Null
_ = sync.Pool{}
_ = codes.Unset
)
var _ Handler = UnimplementedHandler{}
// UnimplementedHandler is no-op Handler which returns http.ErrNotImplemented.
type UnimplementedHandler struct{}
// CreateUsers implements createUsers operation.
var _ Handler = UnimplementedHandler{}
// CreateCard implements createCard operation.
//
// Creates a new Users and persists it to storage.
// Creates a new Card and persists it to storage.
//
// POST /users
func (UnimplementedHandler) CreateUsers(ctx context.Context, req CreateUsersReq) (r CreateUsersRes, _ error) {
// POST /cards
func (UnimplementedHandler) CreateCard(ctx context.Context, req *CreateCardReq) (r CreateCardRes, _ error) {
return r, ht.ErrNotImplemented
}
// DeleteUsers implements deleteUsers operation.
// CreateGroup implements createGroup operation.
//
// Deletes the Users with the requested ID.
// Creates a new Group and persists it to storage.
//
// POST /groups
func (UnimplementedHandler) CreateGroup(ctx context.Context, req *CreateGroupReq) (r CreateGroupRes, _ error) {
return r, ht.ErrNotImplemented
}
// CreateUser implements createUser operation.
//
// Creates a new User and persists it to storage.
//
// POST /users
func (UnimplementedHandler) CreateUser(ctx context.Context, req *CreateUserReq) (r CreateUserRes, _ error) {
return r, ht.ErrNotImplemented
}
// DeleteCard implements deleteCard operation.
//
// Deletes the Card with the requested ID.
//
// DELETE /cards/{id}
func (UnimplementedHandler) DeleteCard(ctx context.Context, params DeleteCardParams) (r DeleteCardRes, _ error) {
return r, ht.ErrNotImplemented
}
// DeleteGroup implements deleteGroup operation.
//
// Deletes the Group with the requested ID.
//
// DELETE /groups/{id}
func (UnimplementedHandler) DeleteGroup(ctx context.Context, params DeleteGroupParams) (r DeleteGroupRes, _ error) {
return r, ht.ErrNotImplemented
}
// DeleteUser implements deleteUser operation.
//
// Deletes the User with the requested ID.
//
// DELETE /users/{id}
func (UnimplementedHandler) DeleteUsers(ctx context.Context, params DeleteUsersParams) (r DeleteUsersRes, _ error) {
func (UnimplementedHandler) DeleteUser(ctx context.Context, params DeleteUserParams) (r DeleteUserRes, _ error) {
return r, ht.ErrNotImplemented
}
// DrawDone implements drawDone operation.
//
// PUT /users/{id}/d
func (UnimplementedHandler) DrawDone(ctx context.Context, params DrawDoneParams) (r DrawDoneNoContent, _ error) {
return r, ht.ErrNotImplemented
// Draws a card item as done.
//
// PUT /cards/{id}/d
func (UnimplementedHandler) DrawDone(ctx context.Context, params DrawDoneParams) error {
return ht.ErrNotImplemented
}
// DrawStart implements drawStart operation.
//
// PATCH /users/{id}/start
func (UnimplementedHandler) DrawStart(ctx context.Context, params DrawStartParams) (r DrawStartNoContent, _ error) {
// Draws a card item as done.
//
// PATCH /users/{id}/card/start
func (UnimplementedHandler) DrawStart(ctx context.Context, params DrawStartParams) error {
return ht.ErrNotImplemented
}
// ListCard implements listCard operation.
//
// List Cards.
//
// GET /cards
func (UnimplementedHandler) ListCard(ctx context.Context, params ListCardParams) (r ListCardRes, _ error) {
return r, ht.ErrNotImplemented
}
// ListUsers implements listUsers operation.
// ListGroup implements listGroup operation.
//
// List Groups.
//
// GET /groups
func (UnimplementedHandler) ListGroup(ctx context.Context, params ListGroupParams) (r ListGroupRes, _ error) {
return r, ht.ErrNotImplemented
}
// ListGroupUsers implements listGroupUsers operation.
//
// List attached Users.
//
// GET /groups/{id}/users
func (UnimplementedHandler) ListGroupUsers(ctx context.Context, params ListGroupUsersParams) (r ListGroupUsersRes, _ error) {
return r, ht.ErrNotImplemented
}
// ListUser implements listUser operation.
//
// List Users.
//
// GET /users
func (UnimplementedHandler) ListUsers(ctx context.Context, params ListUsersParams) (r ListUsersRes, _ error) {
func (UnimplementedHandler) ListUser(ctx context.Context, params ListUserParams) (r ListUserRes, _ error) {
return r, ht.ErrNotImplemented
}
// ReadUsers implements readUsers operation.
// ListUserCard implements listUserCard operation.
//
// Finds the Users with the requested ID and returns it.
// List attached Cards.
//
// GET /users/{id}/card
func (UnimplementedHandler) ListUserCard(ctx context.Context, params ListUserCardParams) (r ListUserCardRes, _ error) {
return r, ht.ErrNotImplemented
}
// ReadCard implements readCard operation.
//
// Finds the Card with the requested ID and returns it.
//
// GET /cards/{id}
func (UnimplementedHandler) ReadCard(ctx context.Context, params ReadCardParams) (r ReadCardRes, _ error) {
return r, ht.ErrNotImplemented
}
// ReadCardOwner implements readCardOwner operation.
//
// Find the attached User of the Card with the given ID.
//
// GET /cards/{id}/owner
func (UnimplementedHandler) ReadCardOwner(ctx context.Context, params ReadCardOwnerParams) (r ReadCardOwnerRes, _ error) {
return r, ht.ErrNotImplemented
}
// ReadGroup implements readGroup operation.
//
// Finds the Group with the requested ID and returns it.
//
// GET /groups/{id}
func (UnimplementedHandler) ReadGroup(ctx context.Context, params ReadGroupParams) (r ReadGroupRes, _ error) {
return r, ht.ErrNotImplemented
}
// ReadUser implements readUser operation.
//
// Finds the User with the requested ID and returns it.
//
// GET /users/{id}
func (UnimplementedHandler) ReadUsers(ctx context.Context, params ReadUsersParams) (r ReadUsersRes, _ error) {
func (UnimplementedHandler) ReadUser(ctx context.Context, params ReadUserParams) (r ReadUserRes, _ error) {
return r, ht.ErrNotImplemented
}
// UpdateUsers implements updateUsers operation.
// UpdateCard implements updateCard operation.
//
// Updates a Users and persists changes to storage.
// Updates a Card and persists changes to storage.
//
// PATCH /users/{id}
func (UnimplementedHandler) UpdateUsers(ctx context.Context, req UpdateUsersReq, params UpdateUsersParams) (r UpdateUsersRes, _ error) {
// PATCH /cards/{id}
func (UnimplementedHandler) UpdateCard(ctx context.Context, req *UpdateCardReq, params UpdateCardParams) (r UpdateCardRes, _ error) {
return r, ht.ErrNotImplemented
}
// UpdateGroup implements updateGroup operation.
//
// Updates a Group and persists changes to storage.
//
// PATCH /groups/{id}
func (UnimplementedHandler) UpdateGroup(ctx context.Context, req *UpdateGroupReq, params UpdateGroupParams) (r UpdateGroupRes, _ error) {
return r, ht.ErrNotImplemented
}
// UpdateUser implements updateUser operation.
//
// Updates a User and persists changes to storage.
//
// PATCH /users/{id}
func (UnimplementedHandler) UpdateUser(ctx context.Context, req *UpdateUserReq, params UpdateUserParams) (r UpdateUserRes, _ error) {
return r, ht.ErrNotImplemented
}

View File

@ -3,250 +3,36 @@
package ogent
import (
"bytes"
"context"
"fmt"
"io"
"math"
"math/big"
"math/bits"
"net"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-faster/errors"
"github.com/go-faster/jx"
"github.com/google/uuid"
"github.com/ogen-go/ogen/conv"
ht "github.com/ogen-go/ogen/http"
"github.com/ogen-go/ogen/json"
"github.com/ogen-go/ogen/otelogen"
"github.com/ogen-go/ogen/uri"
"github.com/ogen-go/ogen/validate"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
// No-op definition for keeping imports.
var (
_ = context.Background()
_ = fmt.Stringer(nil)
_ = strings.Builder{}
_ = errors.Is
_ = sort.Ints
_ = http.MethodGet
_ = io.Copy
_ = json.Marshal
_ = bytes.NewReader
_ = strconv.ParseInt
_ = time.Time{}
_ = conv.ToInt32
_ = uuid.UUID{}
_ = uri.PathEncoder{}
_ = url.URL{}
_ = math.Mod
_ = bits.LeadingZeros64
_ = big.Rat{}
_ = validate.Int{}
_ = ht.NewRequest
_ = net.IP{}
_ = otelogen.Version
_ = attribute.KeyValue{}
_ = trace.TraceIDFromHex
_ = otel.GetTracerProvider
_ = metric.NewNoopMeterProvider
_ = regexp.MustCompile
_ = jx.Null
_ = sync.Pool{}
_ = codes.Unset
)
func (s CreateUsersReq) Validate() error {
var failures []validate.FieldError
if err := func() error {
if s.Percentage.Set {
if err := func() error {
if err := (validate.Float{}).Validate(float64(s.Percentage.Value)); err != nil {
return errors.Wrap(err, "float")
}
return nil
}(); err != nil {
return err
}
}
return nil
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "percentage",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s ListUsersOKApplicationJSON) Validate() error {
func (s ListCardOKApplicationJSON) Validate() error {
if s == nil {
return errors.New("nil is invalid value")
}
var failures []validate.FieldError
for i, elem := range s {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
func (s ListGroupOKApplicationJSON) Validate() error {
if s == nil {
return errors.New("nil is invalid value")
}
return nil
}
func (s UpdateUsersReq) Validate() error {
var failures []validate.FieldError
if err := func() error {
if s.Percentage.Set {
if err := func() error {
if err := (validate.Float{}).Validate(float64(s.Percentage.Value)); err != nil {
return errors.Wrap(err, "float")
}
return nil
}(); err != nil {
return err
}
}
return nil
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "percentage",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
func (s ListGroupUsersOKApplicationJSON) Validate() error {
if s == nil {
return errors.New("nil is invalid value")
}
return nil
}
func (s UsersCreate) Validate() error {
var failures []validate.FieldError
if err := func() error {
if s.Percentage.Set {
if err := func() error {
if err := (validate.Float{}).Validate(float64(s.Percentage.Value)); err != nil {
return errors.Wrap(err, "float")
}
return nil
}(); err != nil {
return err
}
}
return nil
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "percentage",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
func (s ListUserCardOKApplicationJSON) Validate() error {
if s == nil {
return errors.New("nil is invalid value")
}
return nil
}
func (s UsersList) Validate() error {
var failures []validate.FieldError
if err := func() error {
if s.Percentage.Set {
if err := func() error {
if err := (validate.Float{}).Validate(float64(s.Percentage.Value)); err != nil {
return errors.Wrap(err, "float")
}
return nil
}(); err != nil {
return err
}
}
return nil
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "percentage",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s UsersRead) Validate() error {
var failures []validate.FieldError
if err := func() error {
if s.Percentage.Set {
if err := func() error {
if err := (validate.Float{}).Validate(float64(s.Percentage.Value)); err != nil {
return errors.Wrap(err, "float")
}
return nil
}(); err != nil {
return err
}
}
return nil
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "percentage",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s UsersUpdate) Validate() error {
var failures []validate.FieldError
if err := func() error {
if s.Percentage.Set {
if err := func() error {
if err := (validate.Float{}).Validate(float64(s.Percentage.Value)); err != nil {
return errors.Wrap(err, "float")
}
return nil
}(); err != nil {
return err
}
}
return nil
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "percentage",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
func (s ListUserOKApplicationJSON) Validate() error {
if s == nil {
return errors.New("nil is invalid value")
}
return nil
}

View File

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT.
// Code generated by ent, DO NOT EDIT.
package ogent
@ -7,7 +7,9 @@ import (
"net/http"
"t/ent"
"t/ent/users"
"t/ent/card"
"t/ent/group"
"t/ent/user"
"github.com/go-faster/jx"
)
@ -27,63 +29,27 @@ func rawError(err error) jx.Raw {
return e.Bytes()
}
// CreateUsers handles POST /users-slice requests.
func (h *OgentHandler) CreateUsers(ctx context.Context, req CreateUsersReq) (CreateUsersRes, error) {
b := h.client.Users.Create()
// CreateCard handles POST /cards requests.
func (h *OgentHandler) CreateCard(ctx context.Context, req *CreateCardReq) (CreateCardRes, error) {
b := h.client.Card.Create()
// Add all fields.
b.SetUser(req.User)
if v, ok := req.Chara.Get(); ok {
b.SetChara(v)
}
if v, ok := req.Skill.Get(); ok {
b.SetSkill(v)
}
if v, ok := req.Hp.Get(); ok {
b.SetHp(v)
}
if v, ok := req.Attack.Get(); ok {
b.SetAttack(v)
}
if v, ok := req.Defense.Get(); ok {
b.SetDefense(v)
}
if v, ok := req.Critical.Get(); ok {
b.SetCritical(v)
}
if v, ok := req.Battle.Get(); ok {
b.SetBattle(v)
}
if v, ok := req.Win.Get(); ok {
b.SetWin(v)
}
if v, ok := req.Day.Get(); ok {
b.SetDay(v)
}
if v, ok := req.Percentage.Get(); ok {
b.SetPercentage(v)
}
if v, ok := req.Limit.Get(); ok {
b.SetLimit(v)
if v, ok := req.Card.Get(); ok {
b.SetCard(v)
}
if v, ok := req.Status.Get(); ok {
b.SetStatus(v)
}
if v, ok := req.Comment.Get(); ok {
b.SetComment(v)
}
if v, ok := req.CreatedAt.Get(); ok {
b.SetCreatedAt(v)
}
if v, ok := req.Next.Get(); ok {
b.SetNext(v)
}
if v, ok := req.UpdatedAt.Get(); ok {
b.SetUpdatedAt(v)
if v, ok := req.Cp.Get(); ok {
b.SetCp(v)
}
if v, ok := req.URL.Get(); ok {
b.SetURL(v)
}
if v, ok := req.CreatedAt.Get(); ok {
b.SetCreatedAt(v)
}
// Add all edges.
b.SetOwnerID(req.Owner)
// Persist to storage.
e, err := b.Save(ctx)
if err != nil {
@ -106,18 +72,18 @@ func (h *OgentHandler) CreateUsers(ctx context.Context, req CreateUsersReq) (Cre
}
}
// Reload the entity to attach all eager-loaded edges.
q := h.client.Users.Query().Where(users.ID(e.ID))
q := h.client.Card.Query().Where(card.ID(e.ID))
e, err = q.Only(ctx)
if err != nil {
// This should never happen.
return nil, err
}
return NewUsersCreate(e), nil
return NewCardCreate(e), nil
}
// ReadUsers handles GET /users-slice/{id} requests.
func (h *OgentHandler) ReadUsers(ctx context.Context, params ReadUsersParams) (ReadUsersRes, error) {
q := h.client.Users.Query().Where(users.IDEQ(params.ID))
// ReadCard handles GET /cards/{id} requests.
func (h *OgentHandler) ReadCard(ctx context.Context, params ReadCardParams) (ReadCardRes, error) {
q := h.client.Card.Query().Where(card.IDEQ(params.ID))
e, err := q.Only(ctx)
if err != nil {
switch {
@ -138,50 +104,17 @@ func (h *OgentHandler) ReadUsers(ctx context.Context, params ReadUsersParams) (R
return nil, err
}
}
return NewUsersRead(e), nil
return NewCardRead(e), nil
}
// UpdateUsers handles PATCH /users-slice/{id} requests.
func (h *OgentHandler) UpdateUsers(ctx context.Context, req UpdateUsersReq, params UpdateUsersParams) (UpdateUsersRes, error) {
b := h.client.Users.UpdateOneID(params.ID)
// UpdateCard handles PATCH /cards/{id} requests.
func (h *OgentHandler) UpdateCard(ctx context.Context, req *UpdateCardReq, params UpdateCardParams) (UpdateCardRes, error) {
b := h.client.Card.UpdateOneID(params.ID)
// Add all fields.
if v, ok := req.Hp.Get(); ok {
b.SetHp(v)
}
if v, ok := req.Attack.Get(); ok {
b.SetAttack(v)
}
if v, ok := req.Defense.Get(); ok {
b.SetDefense(v)
}
if v, ok := req.Critical.Get(); ok {
b.SetCritical(v)
}
if v, ok := req.Battle.Get(); ok {
b.SetBattle(v)
}
if v, ok := req.Win.Get(); ok {
b.SetWin(v)
}
if v, ok := req.Day.Get(); ok {
b.SetDay(v)
}
if v, ok := req.Percentage.Get(); ok {
b.SetPercentage(v)
}
if v, ok := req.Limit.Get(); ok {
b.SetLimit(v)
}
if v, ok := req.Comment.Get(); ok {
b.SetComment(v)
}
if v, ok := req.Next.Get(); ok {
b.SetNext(v)
}
if v, ok := req.UpdatedAt.Get(); ok {
b.SetUpdatedAt(v)
}
// Add all edges.
if v, ok := req.Owner.Get(); ok {
b.SetOwnerID(v)
}
// Persist to storage.
e, err := b.Save(ctx)
if err != nil {
@ -204,18 +137,18 @@ func (h *OgentHandler) UpdateUsers(ctx context.Context, req UpdateUsersReq, para
}
}
// Reload the entity to attach all eager-loaded edges.
q := h.client.Users.Query().Where(users.ID(e.ID))
q := h.client.Card.Query().Where(card.ID(e.ID))
e, err = q.Only(ctx)
if err != nil {
// This should never happen.
return nil, err
}
return NewUsersUpdate(e), nil
return NewCardUpdate(e), nil
}
// DeleteUsers handles DELETE /users-slice/{id} requests.
func (h *OgentHandler) DeleteUsers(ctx context.Context, params DeleteUsersParams) (DeleteUsersRes, error) {
err := h.client.Users.DeleteOneID(params.ID).Exec(ctx)
// DeleteCard handles DELETE /cards/{id} requests.
func (h *OgentHandler) DeleteCard(ctx context.Context, params DeleteCardParams) (DeleteCardRes, error) {
err := h.client.Card.DeleteOneID(params.ID).Exec(ctx)
if err != nil {
switch {
case ent.IsNotFound(err):
@ -235,13 +168,13 @@ func (h *OgentHandler) DeleteUsers(ctx context.Context, params DeleteUsersParams
return nil, err
}
}
return new(DeleteUsersNoContent), nil
return new(DeleteCardNoContent), nil
}
// ListUsers handles GET /users-slice requests.
func (h *OgentHandler) ListUsers(ctx context.Context, params ListUsersParams) (ListUsersRes, error) {
q := h.client.Users.Query()
// ListCard handles GET /cards requests.
func (h *OgentHandler) ListCard(ctx context.Context, params ListCardParams) (ListCardRes, error) {
q := h.client.Card.Query()
page := 1
if v, ok := params.Page.Get(); ok {
page = v
@ -250,7 +183,9 @@ func (h *OgentHandler) ListUsers(ctx context.Context, params ListUsersParams) (L
if v, ok := params.ItemsPerPage.Get(); ok {
itemsPerPage = v
}
es, err := q.Limit(itemsPerPage).Offset((page - 1) * itemsPerPage).All(ctx)
q.Limit(itemsPerPage).Offset((page - 1) * itemsPerPage)
es, err := q.All(ctx)
if err != nil {
switch {
case ent.IsNotFound(err):
@ -270,5 +205,454 @@ func (h *OgentHandler) ListUsers(ctx context.Context, params ListUsersParams) (L
return nil, err
}
}
return ListUsersOKApplicationJSON(NewUsersLists(es)), nil
r := NewCardLists(es)
return (*ListCardOKApplicationJSON)(&r), nil
}
// ReadCardOwner handles GET /cards/{id}/owner requests.
func (h *OgentHandler) ReadCardOwner(ctx context.Context, params ReadCardOwnerParams) (ReadCardOwnerRes, error) {
q := h.client.Card.Query().Where(card.IDEQ(params.ID)).QueryOwner()
e, err := q.Only(ctx)
if err != nil {
switch {
case ent.IsNotFound(err):
return &R404{
Code: http.StatusNotFound,
Status: http.StatusText(http.StatusNotFound),
Errors: rawError(err),
}, nil
case ent.IsNotSingular(err):
return &R409{
Code: http.StatusConflict,
Status: http.StatusText(http.StatusConflict),
Errors: rawError(err),
}, nil
default:
// Let the server handle the error.
return nil, err
}
}
return NewCardOwnerRead(e), nil
}
// CreateGroup handles POST /groups requests.
func (h *OgentHandler) CreateGroup(ctx context.Context, req *CreateGroupReq) (CreateGroupRes, error) {
b := h.client.Group.Create()
// Add all fields.
b.SetName(req.Name)
// Add all edges.
b.AddUserIDs(req.Users...)
// Persist to storage.
e, err := b.Save(ctx)
if err != nil {
switch {
case ent.IsNotSingular(err):
return &R409{
Code: http.StatusConflict,
Status: http.StatusText(http.StatusConflict),
Errors: rawError(err),
}, nil
case ent.IsConstraintError(err):
return &R409{
Code: http.StatusConflict,
Status: http.StatusText(http.StatusConflict),
Errors: rawError(err),
}, nil
default:
// Let the server handle the error.
return nil, err
}
}
// Reload the entity to attach all eager-loaded edges.
q := h.client.Group.Query().Where(group.ID(e.ID))
e, err = q.Only(ctx)
if err != nil {
// This should never happen.
return nil, err
}
return NewGroupCreate(e), nil
}
// ReadGroup handles GET /groups/{id} requests.
func (h *OgentHandler) ReadGroup(ctx context.Context, params ReadGroupParams) (ReadGroupRes, error) {
q := h.client.Group.Query().Where(group.IDEQ(params.ID))
e, err := q.Only(ctx)
if err != nil {
switch {
case ent.IsNotFound(err):
return &R404{
Code: http.StatusNotFound,
Status: http.StatusText(http.StatusNotFound),
Errors: rawError(err),
}, nil
case ent.IsNotSingular(err):
return &R409{
Code: http.StatusConflict,
Status: http.StatusText(http.StatusConflict),
Errors: rawError(err),
}, nil
default:
// Let the server handle the error.
return nil, err
}
}
return NewGroupRead(e), nil
}
// UpdateGroup handles PATCH /groups/{id} requests.
func (h *OgentHandler) UpdateGroup(ctx context.Context, req *UpdateGroupReq, params UpdateGroupParams) (UpdateGroupRes, error) {
b := h.client.Group.UpdateOneID(params.ID)
// Add all fields.
if v, ok := req.Name.Get(); ok {
b.SetName(v)
}
// Add all edges.
if req.Users != nil {
b.ClearUsers().AddUserIDs(req.Users...)
}
// Persist to storage.
e, err := b.Save(ctx)
if err != nil {
switch {
case ent.IsNotFound(err):
return &R404{
Code: http.StatusNotFound,
Status: http.StatusText(http.StatusNotFound),
Errors: rawError(err),
}, nil
case ent.IsConstraintError(err):
return &R409{
Code: http.StatusConflict,
Status: http.StatusText(http.StatusConflict),
Errors: rawError(err),
}, nil
default:
// Let the server handle the error.
return nil, err
}
}
// Reload the entity to attach all eager-loaded edges.
q := h.client.Group.Query().Where(group.ID(e.ID))
e, err = q.Only(ctx)
if err != nil {
// This should never happen.
return nil, err
}
return NewGroupUpdate(e), nil
}
// DeleteGroup handles DELETE /groups/{id} requests.
func (h *OgentHandler) DeleteGroup(ctx context.Context, params DeleteGroupParams) (DeleteGroupRes, error) {
err := h.client.Group.DeleteOneID(params.ID).Exec(ctx)
if err != nil {
switch {
case ent.IsNotFound(err):
return &R404{
Code: http.StatusNotFound,
Status: http.StatusText(http.StatusNotFound),
Errors: rawError(err),
}, nil
case ent.IsConstraintError(err):
return &R409{
Code: http.StatusConflict,
Status: http.StatusText(http.StatusConflict),
Errors: rawError(err),
}, nil
default:
// Let the server handle the error.
return nil, err
}
}
return new(DeleteGroupNoContent), nil
}
// ListGroup handles GET /groups requests.
func (h *OgentHandler) ListGroup(ctx context.Context, params ListGroupParams) (ListGroupRes, error) {
q := h.client.Group.Query()
page := 1
if v, ok := params.Page.Get(); ok {
page = v
}
itemsPerPage := 30
if v, ok := params.ItemsPerPage.Get(); ok {
itemsPerPage = v
}
q.Limit(itemsPerPage).Offset((page - 1) * itemsPerPage)
es, err := q.All(ctx)
if err != nil {
switch {
case ent.IsNotFound(err):
return &R404{
Code: http.StatusNotFound,
Status: http.StatusText(http.StatusNotFound),
Errors: rawError(err),
}, nil
case ent.IsNotSingular(err):
return &R409{
Code: http.StatusConflict,
Status: http.StatusText(http.StatusConflict),
Errors: rawError(err),
}, nil
default:
// Let the server handle the error.
return nil, err
}
}
r := NewGroupLists(es)
return (*ListGroupOKApplicationJSON)(&r), nil
}
// ListGroupUsers handles GET /groups/{id}/users requests.
func (h *OgentHandler) ListGroupUsers(ctx context.Context, params ListGroupUsersParams) (ListGroupUsersRes, error) {
q := h.client.Group.Query().Where(group.IDEQ(params.ID)).QueryUsers()
page := 1
if v, ok := params.Page.Get(); ok {
page = v
}
itemsPerPage := 30
if v, ok := params.ItemsPerPage.Get(); ok {
itemsPerPage = v
}
q.Limit(itemsPerPage).Offset((page - 1) * itemsPerPage)
es, err := q.All(ctx)
if err != nil {
switch {
case ent.IsNotFound(err):
return &R404{
Code: http.StatusNotFound,
Status: http.StatusText(http.StatusNotFound),
Errors: rawError(err),
}, nil
case ent.IsNotSingular(err):
return &R409{
Code: http.StatusConflict,
Status: http.StatusText(http.StatusConflict),
Errors: rawError(err),
}, nil
default:
// Let the server handle the error.
return nil, err
}
}
r := NewGroupUsersLists(es)
return (*ListGroupUsersOKApplicationJSON)(&r), nil
}
// CreateUser handles POST /users requests.
func (h *OgentHandler) CreateUser(ctx context.Context, req *CreateUserReq) (CreateUserRes, error) {
b := h.client.User.Create()
// Add all fields.
b.SetUsername(req.Username)
if v, ok := req.CreatedAt.Get(); ok {
b.SetCreatedAt(v)
}
if v, ok := req.UpdatedAt.Get(); ok {
b.SetUpdatedAt(v)
}
if v, ok := req.Next.Get(); ok {
b.SetNext(v)
}
// Add all edges.
b.AddCardIDs(req.Card...)
// Persist to storage.
e, err := b.Save(ctx)
if err != nil {
switch {
case ent.IsNotSingular(err):
return &R409{
Code: http.StatusConflict,
Status: http.StatusText(http.StatusConflict),
Errors: rawError(err),
}, nil
case ent.IsConstraintError(err):
return &R409{
Code: http.StatusConflict,
Status: http.StatusText(http.StatusConflict),
Errors: rawError(err),
}, nil
default:
// Let the server handle the error.
return nil, err
}
}
// Reload the entity to attach all eager-loaded edges.
q := h.client.User.Query().Where(user.ID(e.ID))
e, err = q.Only(ctx)
if err != nil {
// This should never happen.
return nil, err
}
return NewUserCreate(e), nil
}
// ReadUser handles GET /users/{id} requests.
func (h *OgentHandler) ReadUser(ctx context.Context, params ReadUserParams) (ReadUserRes, error) {
q := h.client.User.Query().Where(user.IDEQ(params.ID))
e, err := q.Only(ctx)
if err != nil {
switch {
case ent.IsNotFound(err):
return &R404{
Code: http.StatusNotFound,
Status: http.StatusText(http.StatusNotFound),
Errors: rawError(err),
}, nil
case ent.IsNotSingular(err):
return &R409{
Code: http.StatusConflict,
Status: http.StatusText(http.StatusConflict),
Errors: rawError(err),
}, nil
default:
// Let the server handle the error.
return nil, err
}
}
return NewUserRead(e), nil
}
// UpdateUser handles PATCH /users/{id} requests.
func (h *OgentHandler) UpdateUser(ctx context.Context, req *UpdateUserReq, params UpdateUserParams) (UpdateUserRes, error) {
b := h.client.User.UpdateOneID(params.ID)
// Add all fields.
if v, ok := req.UpdatedAt.Get(); ok {
b.SetUpdatedAt(v)
}
if v, ok := req.Next.Get(); ok {
b.SetNext(v)
}
// Add all edges.
if req.Card != nil {
b.ClearCard().AddCardIDs(req.Card...)
}
// Persist to storage.
e, err := b.Save(ctx)
if err != nil {
switch {
case ent.IsNotFound(err):
return &R404{
Code: http.StatusNotFound,
Status: http.StatusText(http.StatusNotFound),
Errors: rawError(err),
}, nil
case ent.IsConstraintError(err):
return &R409{
Code: http.StatusConflict,
Status: http.StatusText(http.StatusConflict),
Errors: rawError(err),
}, nil
default:
// Let the server handle the error.
return nil, err
}
}
// Reload the entity to attach all eager-loaded edges.
q := h.client.User.Query().Where(user.ID(e.ID))
e, err = q.Only(ctx)
if err != nil {
// This should never happen.
return nil, err
}
return NewUserUpdate(e), nil
}
// DeleteUser handles DELETE /users/{id} requests.
func (h *OgentHandler) DeleteUser(ctx context.Context, params DeleteUserParams) (DeleteUserRes, error) {
err := h.client.User.DeleteOneID(params.ID).Exec(ctx)
if err != nil {
switch {
case ent.IsNotFound(err):
return &R404{
Code: http.StatusNotFound,
Status: http.StatusText(http.StatusNotFound),
Errors: rawError(err),
}, nil
case ent.IsConstraintError(err):
return &R409{
Code: http.StatusConflict,
Status: http.StatusText(http.StatusConflict),
Errors: rawError(err),
}, nil
default:
// Let the server handle the error.
return nil, err
}
}
return new(DeleteUserNoContent), nil
}
// ListUser handles GET /users requests.
func (h *OgentHandler) ListUser(ctx context.Context, params ListUserParams) (ListUserRes, error) {
q := h.client.User.Query()
page := 1
if v, ok := params.Page.Get(); ok {
page = v
}
itemsPerPage := 30
if v, ok := params.ItemsPerPage.Get(); ok {
itemsPerPage = v
}
q.Limit(itemsPerPage).Offset((page - 1) * itemsPerPage)
es, err := q.All(ctx)
if err != nil {
switch {
case ent.IsNotFound(err):
return &R404{
Code: http.StatusNotFound,
Status: http.StatusText(http.StatusNotFound),
Errors: rawError(err),
}, nil
case ent.IsNotSingular(err):
return &R409{
Code: http.StatusConflict,
Status: http.StatusText(http.StatusConflict),
Errors: rawError(err),
}, nil
default:
// Let the server handle the error.
return nil, err
}
}
r := NewUserLists(es)
return (*ListUserOKApplicationJSON)(&r), nil
}
// ListUserCard handles GET /users/{id}/card requests.
func (h *OgentHandler) ListUserCard(ctx context.Context, params ListUserCardParams) (ListUserCardRes, error) {
q := h.client.User.Query().Where(user.IDEQ(params.ID)).QueryCard()
page := 1
if v, ok := params.Page.Get(); ok {
page = v
}
itemsPerPage := 30
if v, ok := params.ItemsPerPage.Get(); ok {
itemsPerPage = v
}
q.Limit(itemsPerPage).Offset((page - 1) * itemsPerPage)
es, err := q.All(ctx)
if err != nil {
switch {
case ent.IsNotFound(err):
return &R404{
Code: http.StatusNotFound,
Status: http.StatusText(http.StatusNotFound),
Errors: rawError(err),
}, nil
case ent.IsNotSingular(err):
return &R409{
Code: http.StatusConflict,
Status: http.StatusText(http.StatusConflict),
Errors: rawError(err),
}, nil
default:
// Let the server handle the error.
return nil, err
}
}
r := NewUserCardLists(es)
return (*ListUserCardOKApplicationJSON)(&r), nil
}

View File

@ -1,185 +1,463 @@
// Code generated by entc, DO NOT EDIT.
// Code generated by ent, DO NOT EDIT.
package ogent
import "t/ent"
func NewUsersCreate(e *ent.Users) *UsersCreate {
func NewCardCreate(e *ent.Card) *CardCreate {
if e == nil {
return nil
}
return &UsersCreate{
ID: e.ID,
User: e.User,
Chara: NewOptString(e.Chara),
Skill: NewOptInt(e.Skill),
Hp: NewOptInt(e.Hp),
Attack: NewOptInt(e.Attack),
Defense: NewOptInt(e.Defense),
Critical: NewOptInt(e.Critical),
Battle: NewOptInt(e.Battle),
Win: NewOptInt(e.Win),
Day: NewOptInt(e.Day),
Percentage: NewOptFloat64(e.Percentage),
Limit: NewOptBool(e.Limit),
Status: NewOptString(e.Status),
Comment: NewOptString(e.Comment),
CreatedAt: NewOptDateTime(e.CreatedAt),
Next: NewOptString(e.Next),
UpdatedAt: NewOptDateTime(e.UpdatedAt),
URL: NewOptString(e.URL),
}
var ret CardCreate
ret.ID = e.ID
ret.Card = NewOptInt(e.Card)
ret.Status = NewOptString(e.Status)
ret.Cp = NewOptInt(e.Cp)
ret.URL = NewOptString(e.URL)
ret.CreatedAt = NewOptDateTime(e.CreatedAt)
return &ret
}
func NewUsersCreates(es []*ent.Users) []UsersCreate {
func NewCardCreates(es []*ent.Card) []CardCreate {
if len(es) == 0 {
return nil
}
r := make([]UsersCreate, len(es))
r := make([]CardCreate, len(es))
for i, e := range es {
r[i] = NewUsersCreate(e).Elem()
r[i] = NewCardCreate(e).Elem()
}
return r
}
func (u *UsersCreate) Elem() UsersCreate {
if u != nil {
return UsersCreate{}
func (c *CardCreate) Elem() CardCreate {
if c == nil {
return CardCreate{}
}
return *u
return *c
}
func NewUsersList(e *ent.Users) *UsersList {
func NewCardList(e *ent.Card) *CardList {
if e == nil {
return nil
}
return &UsersList{
ID: e.ID,
User: e.User,
Chara: NewOptString(e.Chara),
Skill: NewOptInt(e.Skill),
Hp: NewOptInt(e.Hp),
Attack: NewOptInt(e.Attack),
Defense: NewOptInt(e.Defense),
Critical: NewOptInt(e.Critical),
Battle: NewOptInt(e.Battle),
Win: NewOptInt(e.Win),
Day: NewOptInt(e.Day),
Percentage: NewOptFloat64(e.Percentage),
Limit: NewOptBool(e.Limit),
Status: NewOptString(e.Status),
Comment: NewOptString(e.Comment),
CreatedAt: NewOptDateTime(e.CreatedAt),
Next: NewOptString(e.Next),
UpdatedAt: NewOptDateTime(e.UpdatedAt),
URL: NewOptString(e.URL),
}
var ret CardList
ret.ID = e.ID
ret.Card = NewOptInt(e.Card)
ret.Status = NewOptString(e.Status)
ret.Cp = NewOptInt(e.Cp)
ret.URL = NewOptString(e.URL)
ret.CreatedAt = NewOptDateTime(e.CreatedAt)
return &ret
}
func NewUsersLists(es []*ent.Users) []UsersList {
func NewCardLists(es []*ent.Card) []CardList {
if len(es) == 0 {
return nil
}
r := make([]UsersList, len(es))
r := make([]CardList, len(es))
for i, e := range es {
r[i] = NewUsersList(e).Elem()
r[i] = NewCardList(e).Elem()
}
return r
}
func (u *UsersList) Elem() UsersList {
if u != nil {
return UsersList{}
func (c *CardList) Elem() CardList {
if c == nil {
return CardList{}
}
return *u
return *c
}
func NewUsersRead(e *ent.Users) *UsersRead {
func NewCardRead(e *ent.Card) *CardRead {
if e == nil {
return nil
}
return &UsersRead{
ID: e.ID,
User: e.User,
Chara: NewOptString(e.Chara),
Skill: NewOptInt(e.Skill),
Hp: NewOptInt(e.Hp),
Attack: NewOptInt(e.Attack),
Defense: NewOptInt(e.Defense),
Critical: NewOptInt(e.Critical),
Battle: NewOptInt(e.Battle),
Win: NewOptInt(e.Win),
Day: NewOptInt(e.Day),
Percentage: NewOptFloat64(e.Percentage),
Limit: NewOptBool(e.Limit),
Status: NewOptString(e.Status),
Comment: NewOptString(e.Comment),
CreatedAt: NewOptDateTime(e.CreatedAt),
Next: NewOptString(e.Next),
UpdatedAt: NewOptDateTime(e.UpdatedAt),
URL: NewOptString(e.URL),
}
var ret CardRead
ret.ID = e.ID
ret.Card = NewOptInt(e.Card)
ret.Status = NewOptString(e.Status)
ret.Cp = NewOptInt(e.Cp)
ret.URL = NewOptString(e.URL)
ret.CreatedAt = NewOptDateTime(e.CreatedAt)
return &ret
}
func NewUsersReads(es []*ent.Users) []UsersRead {
func NewCardReads(es []*ent.Card) []CardRead {
if len(es) == 0 {
return nil
}
r := make([]UsersRead, len(es))
r := make([]CardRead, len(es))
for i, e := range es {
r[i] = NewUsersRead(e).Elem()
r[i] = NewCardRead(e).Elem()
}
return r
}
func (u *UsersRead) Elem() UsersRead {
if u != nil {
return UsersRead{}
func (c *CardRead) Elem() CardRead {
if c == nil {
return CardRead{}
}
return *u
return *c
}
func NewUsersUpdate(e *ent.Users) *UsersUpdate {
func NewCardUpdate(e *ent.Card) *CardUpdate {
if e == nil {
return nil
}
return &UsersUpdate{
ID: e.ID,
User: e.User,
Chara: NewOptString(e.Chara),
Skill: NewOptInt(e.Skill),
Hp: NewOptInt(e.Hp),
Attack: NewOptInt(e.Attack),
Defense: NewOptInt(e.Defense),
Critical: NewOptInt(e.Critical),
Battle: NewOptInt(e.Battle),
Win: NewOptInt(e.Win),
Day: NewOptInt(e.Day),
Percentage: NewOptFloat64(e.Percentage),
Limit: NewOptBool(e.Limit),
Status: NewOptString(e.Status),
Comment: NewOptString(e.Comment),
CreatedAt: NewOptDateTime(e.CreatedAt),
Next: NewOptString(e.Next),
UpdatedAt: NewOptDateTime(e.UpdatedAt),
URL: NewOptString(e.URL),
}
var ret CardUpdate
ret.ID = e.ID
ret.Card = NewOptInt(e.Card)
ret.Status = NewOptString(e.Status)
ret.Cp = NewOptInt(e.Cp)
ret.URL = NewOptString(e.URL)
ret.CreatedAt = NewOptDateTime(e.CreatedAt)
return &ret
}
func NewUsersUpdates(es []*ent.Users) []UsersUpdate {
func NewCardUpdates(es []*ent.Card) []CardUpdate {
if len(es) == 0 {
return nil
}
r := make([]UsersUpdate, len(es))
r := make([]CardUpdate, len(es))
for i, e := range es {
r[i] = NewUsersUpdate(e).Elem()
r[i] = NewCardUpdate(e).Elem()
}
return r
}
func (u *UsersUpdate) Elem() UsersUpdate {
if u != nil {
return UsersUpdate{}
func (c *CardUpdate) Elem() CardUpdate {
if c == nil {
return CardUpdate{}
}
return *c
}
func NewCardOwnerRead(e *ent.User) *CardOwnerRead {
if e == nil {
return nil
}
var ret CardOwnerRead
ret.ID = e.ID
ret.Username = e.Username
ret.CreatedAt = NewOptDateTime(e.CreatedAt)
ret.UpdatedAt = NewOptDateTime(e.UpdatedAt)
ret.Next = NewOptString(e.Next)
return &ret
}
func NewCardOwnerReads(es []*ent.User) []CardOwnerRead {
if len(es) == 0 {
return nil
}
r := make([]CardOwnerRead, len(es))
for i, e := range es {
r[i] = NewCardOwnerRead(e).Elem()
}
return r
}
func (u *CardOwnerRead) Elem() CardOwnerRead {
if u == nil {
return CardOwnerRead{}
}
return *u
}
func NewGroupCreate(e *ent.Group) *GroupCreate {
if e == nil {
return nil
}
var ret GroupCreate
ret.ID = e.ID
ret.Name = e.Name
return &ret
}
func NewGroupCreates(es []*ent.Group) []GroupCreate {
if len(es) == 0 {
return nil
}
r := make([]GroupCreate, len(es))
for i, e := range es {
r[i] = NewGroupCreate(e).Elem()
}
return r
}
func (gr *GroupCreate) Elem() GroupCreate {
if gr == nil {
return GroupCreate{}
}
return *gr
}
func NewGroupList(e *ent.Group) *GroupList {
if e == nil {
return nil
}
var ret GroupList
ret.ID = e.ID
ret.Name = e.Name
return &ret
}
func NewGroupLists(es []*ent.Group) []GroupList {
if len(es) == 0 {
return nil
}
r := make([]GroupList, len(es))
for i, e := range es {
r[i] = NewGroupList(e).Elem()
}
return r
}
func (gr *GroupList) Elem() GroupList {
if gr == nil {
return GroupList{}
}
return *gr
}
func NewGroupRead(e *ent.Group) *GroupRead {
if e == nil {
return nil
}
var ret GroupRead
ret.ID = e.ID
ret.Name = e.Name
return &ret
}
func NewGroupReads(es []*ent.Group) []GroupRead {
if len(es) == 0 {
return nil
}
r := make([]GroupRead, len(es))
for i, e := range es {
r[i] = NewGroupRead(e).Elem()
}
return r
}
func (gr *GroupRead) Elem() GroupRead {
if gr == nil {
return GroupRead{}
}
return *gr
}
func NewGroupUpdate(e *ent.Group) *GroupUpdate {
if e == nil {
return nil
}
var ret GroupUpdate
ret.ID = e.ID
ret.Name = e.Name
return &ret
}
func NewGroupUpdates(es []*ent.Group) []GroupUpdate {
if len(es) == 0 {
return nil
}
r := make([]GroupUpdate, len(es))
for i, e := range es {
r[i] = NewGroupUpdate(e).Elem()
}
return r
}
func (gr *GroupUpdate) Elem() GroupUpdate {
if gr == nil {
return GroupUpdate{}
}
return *gr
}
func NewGroupUsersList(e *ent.User) *GroupUsersList {
if e == nil {
return nil
}
var ret GroupUsersList
ret.ID = e.ID
ret.Username = e.Username
ret.CreatedAt = NewOptDateTime(e.CreatedAt)
ret.UpdatedAt = NewOptDateTime(e.UpdatedAt)
ret.Next = NewOptString(e.Next)
return &ret
}
func NewGroupUsersLists(es []*ent.User) []GroupUsersList {
if len(es) == 0 {
return nil
}
r := make([]GroupUsersList, len(es))
for i, e := range es {
r[i] = NewGroupUsersList(e).Elem()
}
return r
}
func (u *GroupUsersList) Elem() GroupUsersList {
if u == nil {
return GroupUsersList{}
}
return *u
}
func NewUserCreate(e *ent.User) *UserCreate {
if e == nil {
return nil
}
var ret UserCreate
ret.ID = e.ID
ret.Username = e.Username
ret.CreatedAt = NewOptDateTime(e.CreatedAt)
ret.UpdatedAt = NewOptDateTime(e.UpdatedAt)
ret.Next = NewOptString(e.Next)
return &ret
}
func NewUserCreates(es []*ent.User) []UserCreate {
if len(es) == 0 {
return nil
}
r := make([]UserCreate, len(es))
for i, e := range es {
r[i] = NewUserCreate(e).Elem()
}
return r
}
func (u *UserCreate) Elem() UserCreate {
if u == nil {
return UserCreate{}
}
return *u
}
func NewUserList(e *ent.User) *UserList {
if e == nil {
return nil
}
var ret UserList
ret.ID = e.ID
ret.Username = e.Username
ret.CreatedAt = NewOptDateTime(e.CreatedAt)
ret.UpdatedAt = NewOptDateTime(e.UpdatedAt)
ret.Next = NewOptString(e.Next)
return &ret
}
func NewUserLists(es []*ent.User) []UserList {
if len(es) == 0 {
return nil
}
r := make([]UserList, len(es))
for i, e := range es {
r[i] = NewUserList(e).Elem()
}
return r
}
func (u *UserList) Elem() UserList {
if u == nil {
return UserList{}
}
return *u
}
func NewUserRead(e *ent.User) *UserRead {
if e == nil {
return nil
}
var ret UserRead
ret.ID = e.ID
ret.Username = e.Username
ret.CreatedAt = NewOptDateTime(e.CreatedAt)
ret.UpdatedAt = NewOptDateTime(e.UpdatedAt)
ret.Next = NewOptString(e.Next)
return &ret
}
func NewUserReads(es []*ent.User) []UserRead {
if len(es) == 0 {
return nil
}
r := make([]UserRead, len(es))
for i, e := range es {
r[i] = NewUserRead(e).Elem()
}
return r
}
func (u *UserRead) Elem() UserRead {
if u == nil {
return UserRead{}
}
return *u
}
func NewUserUpdate(e *ent.User) *UserUpdate {
if e == nil {
return nil
}
var ret UserUpdate
ret.ID = e.ID
ret.Username = e.Username
ret.CreatedAt = NewOptDateTime(e.CreatedAt)
ret.UpdatedAt = NewOptDateTime(e.UpdatedAt)
ret.Next = NewOptString(e.Next)
return &ret
}
func NewUserUpdates(es []*ent.User) []UserUpdate {
if len(es) == 0 {
return nil
}
r := make([]UserUpdate, len(es))
for i, e := range es {
r[i] = NewUserUpdate(e).Elem()
}
return r
}
func (u *UserUpdate) Elem() UserUpdate {
if u == nil {
return UserUpdate{}
}
return *u
}
func NewUserCardList(e *ent.Card) *UserCardList {
if e == nil {
return nil
}
var ret UserCardList
ret.ID = e.ID
ret.Card = NewOptInt(e.Card)
ret.Status = NewOptString(e.Status)
ret.Cp = NewOptInt(e.Cp)
ret.URL = NewOptString(e.URL)
ret.CreatedAt = NewOptDateTime(e.CreatedAt)
return &ret
}
func NewUserCardLists(es []*ent.Card) []UserCardList {
if len(es) == 0 {
return nil
}
r := make([]UserCardList, len(es))
for i, e := range es {
r[i] = NewUserCardList(e).Elem()
}
return r
}
func (c *UserCardList) Elem() UserCardList {
if c == nil {
return UserCardList{}
}
return *c
}

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT.
// Code generated by ent, DO NOT EDIT.
package predicate
@ -6,5 +6,11 @@ import (
"entgo.io/ent/dialect/sql"
)
// Users is the predicate function for users builders.
type Users func(*sql.Selector)
// Card is the predicate function for card builders.
type Card func(*sql.Selector)
// Group is the predicate function for group builders.
type Group func(*sql.Selector)
// User is the predicate function for user builders.
type User func(*sql.Selector)

View File

@ -1,10 +1,11 @@
// Code generated by entc, DO NOT EDIT.
// Code generated by ent, DO NOT EDIT.
package ent
import (
"t/ent/card"
"t/ent/schema"
"t/ent/users"
"t/ent/user"
"time"
)
@ -12,93 +13,58 @@ import (
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
usersFields := schema.Users{}.Fields()
_ = usersFields
// usersDescUser is the schema descriptor for user field.
usersDescUser := usersFields[0].Descriptor()
// users.UserValidator is a validator for the "user" field. It is called by the builders before save.
users.UserValidator = func() func(string) error {
validators := usersDescUser.Validators
cardFields := schema.Card{}.Fields()
_ = cardFields
// cardDescCard is the schema descriptor for card field.
cardDescCard := cardFields[0].Descriptor()
// card.DefaultCard holds the default value on creation for the card field.
card.DefaultCard = cardDescCard.Default.(func() int)
// cardDescStatus is the schema descriptor for status field.
cardDescStatus := cardFields[1].Descriptor()
// card.DefaultStatus holds the default value on creation for the status field.
card.DefaultStatus = cardDescStatus.Default.(func() string)
// cardDescCp is the schema descriptor for cp field.
cardDescCp := cardFields[2].Descriptor()
// card.DefaultCp holds the default value on creation for the cp field.
card.DefaultCp = cardDescCp.Default.(func() int)
// cardDescURL is the schema descriptor for url field.
cardDescURL := cardFields[3].Descriptor()
// card.DefaultURL holds the default value on creation for the url field.
card.DefaultURL = cardDescURL.Default.(string)
// cardDescCreatedAt is the schema descriptor for created_at field.
cardDescCreatedAt := cardFields[4].Descriptor()
// card.DefaultCreatedAt holds the default value on creation for the created_at field.
card.DefaultCreatedAt = cardDescCreatedAt.Default.(func() time.Time)
userFields := schema.User{}.Fields()
_ = userFields
// userDescUsername is the schema descriptor for username field.
userDescUsername := userFields[0].Descriptor()
// user.UsernameValidator is a validator for the "username" field. It is called by the builders before save.
user.UsernameValidator = func() func(string) error {
validators := userDescUsername.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
validators[2].(func(string) error),
}
return func(user string) error {
return func(username string) error {
for _, fn := range fns {
if err := fn(user); err != nil {
if err := fn(username); err != nil {
return err
}
}
return nil
}
}()
// usersDescChara is the schema descriptor for chara field.
usersDescChara := usersFields[1].Descriptor()
// users.DefaultChara holds the default value on creation for the chara field.
users.DefaultChara = usersDescChara.Default.(string)
// usersDescSkill is the schema descriptor for skill field.
usersDescSkill := usersFields[2].Descriptor()
// users.DefaultSkill holds the default value on creation for the skill field.
users.DefaultSkill = usersDescSkill.Default.(int)
// usersDescHp is the schema descriptor for hp field.
usersDescHp := usersFields[3].Descriptor()
// users.DefaultHp holds the default value on creation for the hp field.
users.DefaultHp = usersDescHp.Default.(int)
// usersDescAttack is the schema descriptor for attack field.
usersDescAttack := usersFields[4].Descriptor()
// users.DefaultAttack holds the default value on creation for the attack field.
users.DefaultAttack = usersDescAttack.Default.(int)
// usersDescDefense is the schema descriptor for defense field.
usersDescDefense := usersFields[5].Descriptor()
// users.DefaultDefense holds the default value on creation for the defense field.
users.DefaultDefense = usersDescDefense.Default.(int)
// usersDescCritical is the schema descriptor for critical field.
usersDescCritical := usersFields[6].Descriptor()
// users.DefaultCritical holds the default value on creation for the critical field.
users.DefaultCritical = usersDescCritical.Default.(int)
// usersDescBattle is the schema descriptor for battle field.
usersDescBattle := usersFields[7].Descriptor()
// users.DefaultBattle holds the default value on creation for the battle field.
users.DefaultBattle = usersDescBattle.Default.(int)
// usersDescWin is the schema descriptor for win field.
usersDescWin := usersFields[8].Descriptor()
// users.DefaultWin holds the default value on creation for the win field.
users.DefaultWin = usersDescWin.Default.(int)
// usersDescDay is the schema descriptor for day field.
usersDescDay := usersFields[9].Descriptor()
// users.DefaultDay holds the default value on creation for the day field.
users.DefaultDay = usersDescDay.Default.(int)
// usersDescPercentage is the schema descriptor for percentage field.
usersDescPercentage := usersFields[10].Descriptor()
// users.DefaultPercentage holds the default value on creation for the percentage field.
users.DefaultPercentage = usersDescPercentage.Default.(float64)
// usersDescLimit is the schema descriptor for limit field.
usersDescLimit := usersFields[11].Descriptor()
// users.DefaultLimit holds the default value on creation for the limit field.
users.DefaultLimit = usersDescLimit.Default.(bool)
// usersDescStatus is the schema descriptor for status field.
usersDescStatus := usersFields[12].Descriptor()
// users.DefaultStatus holds the default value on creation for the status field.
users.DefaultStatus = usersDescStatus.Default.(string)
// usersDescComment is the schema descriptor for comment field.
usersDescComment := usersFields[13].Descriptor()
// users.DefaultComment holds the default value on creation for the comment field.
users.DefaultComment = usersDescComment.Default.(string)
// usersDescCreatedAt is the schema descriptor for created_at field.
usersDescCreatedAt := usersFields[14].Descriptor()
// users.DefaultCreatedAt holds the default value on creation for the created_at field.
users.DefaultCreatedAt = usersDescCreatedAt.Default.(func() time.Time)
// usersDescNext is the schema descriptor for next field.
usersDescNext := usersFields[15].Descriptor()
// users.DefaultNext holds the default value on creation for the next field.
users.DefaultNext = usersDescNext.Default.(string)
// usersDescUpdatedAt is the schema descriptor for updated_at field.
usersDescUpdatedAt := usersFields[16].Descriptor()
// users.DefaultUpdatedAt holds the default value on creation for the updated_at field.
users.DefaultUpdatedAt = usersDescUpdatedAt.Default.(func() time.Time)
// usersDescURL is the schema descriptor for url field.
usersDescURL := usersFields[17].Descriptor()
// users.DefaultURL holds the default value on creation for the url field.
users.DefaultURL = usersDescURL.Default.(string)
// userDescCreatedAt is the schema descriptor for created_at field.
userDescCreatedAt := userFields[1].Descriptor()
// user.DefaultCreatedAt holds the default value on creation for the created_at field.
user.DefaultCreatedAt = userDescCreatedAt.Default.(func() time.Time)
// userDescUpdatedAt is the schema descriptor for updated_at field.
userDescUpdatedAt := userFields[2].Descriptor()
// user.DefaultUpdatedAt holds the default value on creation for the updated_at field.
user.DefaultUpdatedAt = userDescUpdatedAt.Default.(func() time.Time)
// userDescNext is the schema descriptor for next field.
userDescNext := userFields[3].Descriptor()
// user.DefaultNext holds the default value on creation for the next field.
user.DefaultNext = userDescNext.Default.(string)
}

View File

@ -1,10 +1,10 @@
// Code generated by entc, DO NOT EDIT.
// Code generated by ent, DO NOT EDIT.
package runtime
// The schema-stitching logic is generated in t/ent/runtime.go
const (
Version = "v0.10.0" // Version of ent codegen.
Sum = "h1:9cBomE1fh+WX34DPYQL7tDNAIvhKa3tXvwxuLyhYCMo=" // Sum of ent codegen.
Version = "v0.11.9" // Version of ent codegen.
Sum = "h1:dbbCkAiPVTRBIJwoZctiSYjB7zxQIBOzVSU5H9VYIQI=" // Sum of ent codegen.
)

97
ent/schema/card.go Normal file
View File

@ -0,0 +1,97 @@
package schema
import (
"time"
"math/rand"
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
// Card holds the schema definition for the Card entity.
type Card struct {
ent.Schema
}
var url = "https://card.syui.ai"
var card int
var super string
var cp int
func (Card) Fields() []ent.Field {
return []ent.Field{
field.Int("card").
Immutable().
DefaultFunc(func() int {
rand.Seed(time.Now().UnixNano())
var a = rand.Intn(10)
if a == 1 {
card = rand.Intn(15)
} else {
card = 0
}
if card == 13 {
card = 14
}
return card
}).
Optional(),
field.String("status").
Immutable().
DefaultFunc(func() string {
rand.Seed(time.Now().UnixNano())
var a = rand.Intn(10)
if a == 1 {
super = "super"
} else {
super = "normal"
}
if card == 0 {
super = "normal"
}
return super
}).
Optional(),
field.Int("cp").
Immutable().
DefaultFunc(func() int {
rand.Seed(time.Now().UnixNano())
var cp = rand.Intn(100)
if cp == 1 {
cp = rand.Intn(250)
}
if card > 1 {
cp = cp + rand.Intn(250)
}
if super == "super" {
cp = cp + rand.Intn(500)
}
return cp
}).
Optional(),
field.String("url").
Immutable().
Default(url).
Optional(),
field.Time("created_at").
Immutable().
Optional().
Default(func() time.Time {
return time.Now().In(jst)
}),
}
}
func (Card) Edges() []ent.Edge {
return []ent.Edge{
edge.From("owner", User.Type).
Ref("card").
Unique().
Required(),
}
}

35
ent/schema/group.go Normal file
View File

@ -0,0 +1,35 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// Group holds the schema definition for the Group entity.
type Group struct {
ent.Schema
}
// Fields of the Group.
func (Group) Fields() []ent.Field {
return []ent.Field{
field.String("name"),
}
}
// Edges of the Group.
func (Group) Edges() []ent.Edge {
return []ent.Edge{
edge.To("users", User.Type),
}
}
// Indexes of the Group.
func (Group) Indexes() []ent.Index {
return []ent.Index{
index.Fields("name").Unique(),
}
}

74
ent/schema/user.go Normal file
View File

@ -0,0 +1,74 @@
package schema
import (
"time"
//"regexp"
//"math/rand"
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
//"entgo.io/ent/schema/mixin"
)
var jst,err = time.LoadLocation("Asia/Tokyo")
// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}
func Nextime() (tt string){
t := time.Now().In(jst)
//t := time.Now().Add(time.Hour * 24 * 1).In(jst)
tt = t.Format("20060102")
return
}
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("username").
NotEmpty().
Immutable().
MaxLen(30).
//Match(regexp.MustCompile("[a-z]+$")).
Unique(),
//field.Bool("limit").
//Optional().
//Default(false),
field.Time("created_at").
Immutable().
Optional().
Default(func() time.Time {
return time.Now().In(jst)
}),
field.Time("updated_at").
Optional().
Default(func() time.Time {
return time.Now().In(jst)
}),
field.String("next").
Default(Nextime()).
Optional(),
}
}
// Indexes of the User.
func (User) Indexes() []ent.Index {
return []ent.Index{
index.Fields("username").Unique(),
}
}
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.To("card", Card.Type),
//Unique(),
}
}

View File

@ -1,172 +0,0 @@
package schema
import (
"time"
"regexp"
"entgo.io/ent"
"math/rand"
"entgo.io/ent/schema/field"
"github.com/kyokomi/lottery"
)
type Users struct {
ent.Schema
}
func Random(i int) (l int){
rand.Seed(time.Now().UnixNano())
l = rand.Intn(20)
for l == 0 {
l = rand.Intn(20)
}
return
}
func Kira(i int) (l bool){
lot := lottery.New(rand.New(rand.NewSource(time.Now().UnixNano())))
if lot.Lot(i) {
l = true
} else {
l = false
}
return
}
var jst,err = time.LoadLocation("Asia/Tokyo")
var a = Random(4)
var d = Random(20)
var h = Random(20)
var k = Random(20)
var s = Random(20)
var c = Random(20)
var battle = 2
func StatusR()(status string){
if d == 1 {
var status = "super"
return status
} else {
var status = "normal"
return status
}
return
}
func CharaR()(chara string){
if a == 1 {
var chara = "drai"
return chara
} else if a == 2 {
var chara = "octkat"
return chara
} else if a == 3 {
var chara = "kyosuke"
return chara
} else {
var chara = "ponta"
return chara
}
return
}
func Nextime() (tt string){
t := time.Now().Add(time.Hour * 24 * 1).In(jst)
tt = t.Format("20060102")
return
}
func (Users) Fields() []ent.Field {
return []ent.Field{
field.String("user").
NotEmpty().
Immutable().
MaxLen(7).
Match(regexp.MustCompile("[a-z]+$")).
Unique(),
field.String("chara").
Immutable().
Default(CharaR()).
Optional(),
field.Int("skill").
Immutable().
Optional().
Default(k),
field.Int("hp").
Optional().
Default(h),
field.Int("attack").
Optional().
Default(a),
field.Int("defense").
Optional().
Default(d),
field.Int("critical").
Optional().
Default(c),
field.Int("battle").
Optional().
Default(1),
field.Int("win").
Optional().
Default(0),
field.Int("day").
Optional().
Default(0),
field.Float("percentage").
Optional().
Default(0),
field.Bool("limit").
Optional().
Default(false),
field.String("status").
Immutable().
Optional().
Default(StatusR()),
field.String("comment").
Optional().
Default(""),
field.Time("created_at").
Immutable().
Optional().
Default(func() time.Time {
return time.Now().In(jst)
}),
field.String("next").
Default(Nextime()).
Optional(),
field.Time("updated_at").
Optional().
Default(func() time.Time {
return time.Now().In(jst)
}),
field.String("url").
Immutable().
Optional().
Default("https://syui.cf/api"),
}
}
func (Users) Edges() []ent.Edge {
return []ent.Edge{}
}

View File

@ -1,4 +1,4 @@
// Code generated by entc, DO NOT EDIT.
// Code generated by ent, DO NOT EDIT.
package ent
@ -12,18 +12,16 @@ import (
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Users is the client for interacting with the Users builders.
Users *UsersClient
// Card is the client for interacting with the Card builders.
Card *CardClient
// Group is the client for interacting with the Group builders.
Group *GroupClient
// User is the client for interacting with the User builders.
User *UserClient
// lazily loaded.
client *Client
clientOnce sync.Once
// completion callbacks.
mu sync.Mutex
onCommit []CommitHook
onRollback []RollbackHook
// ctx lives for the life of the transaction. It is
// the same context used by the underlying connection.
ctx context.Context
@ -68,9 +66,9 @@ func (tx *Tx) Commit() error {
var fn Committer = CommitFunc(func(context.Context, *Tx) error {
return txDriver.tx.Commit()
})
tx.mu.Lock()
hooks := append([]CommitHook(nil), tx.onCommit...)
tx.mu.Unlock()
txDriver.mu.Lock()
hooks := append([]CommitHook(nil), txDriver.onCommit...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
@ -79,9 +77,10 @@ func (tx *Tx) Commit() error {
// OnCommit adds a hook to call on commit.
func (tx *Tx) OnCommit(f CommitHook) {
tx.mu.Lock()
defer tx.mu.Unlock()
tx.onCommit = append(tx.onCommit, f)
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onCommit = append(txDriver.onCommit, f)
txDriver.mu.Unlock()
}
type (
@ -123,9 +122,9 @@ func (tx *Tx) Rollback() error {
var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error {
return txDriver.tx.Rollback()
})
tx.mu.Lock()
hooks := append([]RollbackHook(nil), tx.onRollback...)
tx.mu.Unlock()
txDriver.mu.Lock()
hooks := append([]RollbackHook(nil), txDriver.onRollback...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
@ -134,9 +133,10 @@ func (tx *Tx) Rollback() error {
// OnRollback adds a hook to call on rollback.
func (tx *Tx) OnRollback(f RollbackHook) {
tx.mu.Lock()
defer tx.mu.Unlock()
tx.onRollback = append(tx.onRollback, f)
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.
@ -149,7 +149,9 @@ func (tx *Tx) Client() *Client {
}
func (tx *Tx) init() {
tx.Users = NewUsersClient(tx.config)
tx.Card = NewCardClient(tx.config)
tx.Group = NewGroupClient(tx.config)
tx.User = NewUserClient(tx.config)
}
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
@ -159,7 +161,7 @@ func (tx *Tx) init() {
// of them in order to commit or rollback the transaction.
//
// If a closed transaction is embedded in one of the generated entities, and the entity
// applies a query, for example: Users.QueryXXX(), the query will be executed
// applies a query, for example: Card.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.
@ -168,6 +170,10 @@ type txDriver struct {
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.
@ -198,12 +204,12 @@ func (*txDriver) Commit() error { return nil }
func (*txDriver) Rollback() error { return nil }
// Exec calls tx.Exec.
func (tx *txDriver) Exec(ctx context.Context, query string, args, v interface{}) error {
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 interface{}) error {
func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error {
return tx.tx.Query(ctx, query, args, v)
}

165
ent/user.go Normal file
View File

@ -0,0 +1,165 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"t/ent/user"
"time"
"entgo.io/ent/dialect/sql"
)
// User is the model entity for the User schema.
type User struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Username holds the value of the "username" field.
Username string `json:"username,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"`
// Next holds the value of the "next" field.
Next string `json:"next,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the UserQuery when eager-loading is set.
Edges UserEdges `json:"edges"`
group_users *int
}
// UserEdges holds the relations/edges for other nodes in the graph.
type UserEdges struct {
// Card holds the value of the card edge.
Card []*Card `json:"card,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// CardOrErr returns the Card value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) CardOrErr() ([]*Card, error) {
if e.loadedTypes[0] {
return e.Card, nil
}
return nil, &NotLoadedError{edge: "card"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*User) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case user.FieldID:
values[i] = new(sql.NullInt64)
case user.FieldUsername, user.FieldNext:
values[i] = new(sql.NullString)
case user.FieldCreatedAt, user.FieldUpdatedAt:
values[i] = new(sql.NullTime)
case user.ForeignKeys[0]: // group_users
values[i] = new(sql.NullInt64)
default:
return nil, fmt.Errorf("unexpected column %q for type User", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the User fields.
func (u *User) 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 user.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
u.ID = int(value.Int64)
case user.FieldUsername:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field username", values[i])
} else if value.Valid {
u.Username = value.String
}
case user.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 {
u.CreatedAt = value.Time
}
case user.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 {
u.UpdatedAt = value.Time
}
case user.FieldNext:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field next", values[i])
} else if value.Valid {
u.Next = value.String
}
case user.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for edge-field group_users", value)
} else if value.Valid {
u.group_users = new(int)
*u.group_users = int(value.Int64)
}
}
}
return nil
}
// QueryCard queries the "card" edge of the User entity.
func (u *User) QueryCard() *CardQuery {
return NewUserClient(u.config).QueryCard(u)
}
// Update returns a builder for updating this User.
// Note that you need to call User.Unwrap() before calling this method if this User
// was returned from a transaction, and the transaction was committed or rolled back.
func (u *User) Update() *UserUpdateOne {
return NewUserClient(u.config).UpdateOne(u)
}
// Unwrap unwraps the User 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 (u *User) Unwrap() *User {
_tx, ok := u.config.driver.(*txDriver)
if !ok {
panic("ent: User is not a transactional entity")
}
u.config.driver = _tx.drv
return u
}
// String implements the fmt.Stringer.
func (u *User) String() string {
var builder strings.Builder
builder.WriteString("User(")
builder.WriteString(fmt.Sprintf("id=%v, ", u.ID))
builder.WriteString("username=")
builder.WriteString(u.Username)
builder.WriteString(", ")
builder.WriteString("created_at=")
builder.WriteString(u.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(u.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("next=")
builder.WriteString(u.Next)
builder.WriteByte(')')
return builder.String()
}
// Users is a parsable slice of User.
type Users []*User

74
ent/user/user.go Normal file
View File

@ -0,0 +1,74 @@
// Code generated by ent, DO NOT EDIT.
package user
import (
"time"
)
const (
// Label holds the string label denoting the user type in the database.
Label = "user"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldUsername holds the string denoting the username field in the database.
FieldUsername = "username"
// 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"
// FieldNext holds the string denoting the next field in the database.
FieldNext = "next"
// EdgeCard holds the string denoting the card edge name in mutations.
EdgeCard = "card"
// Table holds the table name of the user in the database.
Table = "users"
// CardTable is the table that holds the card relation/edge.
CardTable = "cards"
// CardInverseTable is the table name for the Card entity.
// It exists in this package in order to avoid circular dependency with the "card" package.
CardInverseTable = "cards"
// CardColumn is the table column denoting the card relation/edge.
CardColumn = "user_card"
)
// Columns holds all SQL columns for user fields.
var Columns = []string{
FieldID,
FieldUsername,
FieldCreatedAt,
FieldUpdatedAt,
FieldNext,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "users"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"group_users",
}
// 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 (
// UsernameValidator is a validator for the "username" field. It is called by the builders before save.
UsernameValidator func(string) error
// 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
// DefaultNext holds the default value on creation for the "next" field.
DefaultNext string
)

375
ent/user/where.go Normal file
View File

@ -0,0 +1,375 @@
// Code generated by ent, DO NOT EDIT.
package user
import (
"t/ent/predicate"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.User {
return predicate.User(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.User {
return predicate.User(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.User {
return predicate.User(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.User {
return predicate.User(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.User {
return predicate.User(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.User {
return predicate.User(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.User {
return predicate.User(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.User {
return predicate.User(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.User {
return predicate.User(sql.FieldLTE(FieldID, id))
}
// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ.
func Username(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldUsername, v))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.User {
return predicate.User(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.User {
return predicate.User(sql.FieldEQ(FieldUpdatedAt, v))
}
// Next applies equality check predicate on the "next" field. It's identical to NextEQ.
func Next(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldNext, v))
}
// UsernameEQ applies the EQ predicate on the "username" field.
func UsernameEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldUsername, v))
}
// UsernameNEQ applies the NEQ predicate on the "username" field.
func UsernameNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldUsername, v))
}
// UsernameIn applies the In predicate on the "username" field.
func UsernameIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldUsername, vs...))
}
// UsernameNotIn applies the NotIn predicate on the "username" field.
func UsernameNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldUsername, vs...))
}
// UsernameGT applies the GT predicate on the "username" field.
func UsernameGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldUsername, v))
}
// UsernameGTE applies the GTE predicate on the "username" field.
func UsernameGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldUsername, v))
}
// UsernameLT applies the LT predicate on the "username" field.
func UsernameLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldUsername, v))
}
// UsernameLTE applies the LTE predicate on the "username" field.
func UsernameLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldUsername, v))
}
// UsernameContains applies the Contains predicate on the "username" field.
func UsernameContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldUsername, v))
}
// UsernameHasPrefix applies the HasPrefix predicate on the "username" field.
func UsernameHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldUsername, v))
}
// UsernameHasSuffix applies the HasSuffix predicate on the "username" field.
func UsernameHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldUsername, v))
}
// UsernameEqualFold applies the EqualFold predicate on the "username" field.
func UsernameEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldUsername, v))
}
// UsernameContainsFold applies the ContainsFold predicate on the "username" field.
func UsernameContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldUsername, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.User {
return predicate.User(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.User {
return predicate.User(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.User {
return predicate.User(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.User {
return predicate.User(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.User {
return predicate.User(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.User {
return predicate.User(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.User {
return predicate.User(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.User {
return predicate.User(sql.FieldLTE(FieldCreatedAt, v))
}
// CreatedAtIsNil applies the IsNil predicate on the "created_at" field.
func CreatedAtIsNil() predicate.User {
return predicate.User(sql.FieldIsNull(FieldCreatedAt))
}
// CreatedAtNotNil applies the NotNil predicate on the "created_at" field.
func CreatedAtNotNil() predicate.User {
return predicate.User(sql.FieldNotNull(FieldCreatedAt))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.User {
return predicate.User(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.User {
return predicate.User(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.User {
return predicate.User(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.User {
return predicate.User(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.User {
return predicate.User(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.User {
return predicate.User(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.User {
return predicate.User(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.User {
return predicate.User(sql.FieldLTE(FieldUpdatedAt, v))
}
// UpdatedAtIsNil applies the IsNil predicate on the "updated_at" field.
func UpdatedAtIsNil() predicate.User {
return predicate.User(sql.FieldIsNull(FieldUpdatedAt))
}
// UpdatedAtNotNil applies the NotNil predicate on the "updated_at" field.
func UpdatedAtNotNil() predicate.User {
return predicate.User(sql.FieldNotNull(FieldUpdatedAt))
}
// NextEQ applies the EQ predicate on the "next" field.
func NextEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldNext, v))
}
// NextNEQ applies the NEQ predicate on the "next" field.
func NextNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldNext, v))
}
// NextIn applies the In predicate on the "next" field.
func NextIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldNext, vs...))
}
// NextNotIn applies the NotIn predicate on the "next" field.
func NextNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldNext, vs...))
}
// NextGT applies the GT predicate on the "next" field.
func NextGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldNext, v))
}
// NextGTE applies the GTE predicate on the "next" field.
func NextGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldNext, v))
}
// NextLT applies the LT predicate on the "next" field.
func NextLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldNext, v))
}
// NextLTE applies the LTE predicate on the "next" field.
func NextLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldNext, v))
}
// NextContains applies the Contains predicate on the "next" field.
func NextContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldNext, v))
}
// NextHasPrefix applies the HasPrefix predicate on the "next" field.
func NextHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldNext, v))
}
// NextHasSuffix applies the HasSuffix predicate on the "next" field.
func NextHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldNext, v))
}
// NextIsNil applies the IsNil predicate on the "next" field.
func NextIsNil() predicate.User {
return predicate.User(sql.FieldIsNull(FieldNext))
}
// NextNotNil applies the NotNil predicate on the "next" field.
func NextNotNil() predicate.User {
return predicate.User(sql.FieldNotNull(FieldNext))
}
// NextEqualFold applies the EqualFold predicate on the "next" field.
func NextEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldNext, v))
}
// NextContainsFold applies the ContainsFold predicate on the "next" field.
func NextContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldNext, v))
}
// HasCard applies the HasEdge predicate on the "card" edge.
func HasCard() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, CardTable, CardColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasCardWith applies the HasEdge predicate on the "card" edge with a given conditions (other predicates).
func HasCardWith(preds ...predicate.Card) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(CardInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, CardTable, CardColumn),
)
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.User) predicate.User {
return predicate.User(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.User) predicate.User {
return predicate.User(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.User) predicate.User {
return predicate.User(func(s *sql.Selector) {
p(s.Not())
})
}

292
ent/user_create.go Normal file
View File

@ -0,0 +1,292 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"t/ent/card"
"t/ent/user"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UserCreate is the builder for creating a User entity.
type UserCreate struct {
config
mutation *UserMutation
hooks []Hook
}
// SetUsername sets the "username" field.
func (uc *UserCreate) SetUsername(s string) *UserCreate {
uc.mutation.SetUsername(s)
return uc
}
// SetCreatedAt sets the "created_at" field.
func (uc *UserCreate) SetCreatedAt(t time.Time) *UserCreate {
uc.mutation.SetCreatedAt(t)
return uc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (uc *UserCreate) SetNillableCreatedAt(t *time.Time) *UserCreate {
if t != nil {
uc.SetCreatedAt(*t)
}
return uc
}
// SetUpdatedAt sets the "updated_at" field.
func (uc *UserCreate) SetUpdatedAt(t time.Time) *UserCreate {
uc.mutation.SetUpdatedAt(t)
return uc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (uc *UserCreate) SetNillableUpdatedAt(t *time.Time) *UserCreate {
if t != nil {
uc.SetUpdatedAt(*t)
}
return uc
}
// SetNext sets the "next" field.
func (uc *UserCreate) SetNext(s string) *UserCreate {
uc.mutation.SetNext(s)
return uc
}
// SetNillableNext sets the "next" field if the given value is not nil.
func (uc *UserCreate) SetNillableNext(s *string) *UserCreate {
if s != nil {
uc.SetNext(*s)
}
return uc
}
// AddCardIDs adds the "card" edge to the Card entity by IDs.
func (uc *UserCreate) AddCardIDs(ids ...int) *UserCreate {
uc.mutation.AddCardIDs(ids...)
return uc
}
// AddCard adds the "card" edges to the Card entity.
func (uc *UserCreate) AddCard(c ...*Card) *UserCreate {
ids := make([]int, len(c))
for i := range c {
ids[i] = c[i].ID
}
return uc.AddCardIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (uc *UserCreate) Mutation() *UserMutation {
return uc.mutation
}
// Save creates the User in the database.
func (uc *UserCreate) Save(ctx context.Context) (*User, error) {
uc.defaults()
return withHooks[*User, UserMutation](ctx, uc.sqlSave, uc.mutation, uc.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (uc *UserCreate) SaveX(ctx context.Context) *User {
v, err := uc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (uc *UserCreate) Exec(ctx context.Context) error {
_, err := uc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (uc *UserCreate) ExecX(ctx context.Context) {
if err := uc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (uc *UserCreate) defaults() {
if _, ok := uc.mutation.CreatedAt(); !ok {
v := user.DefaultCreatedAt()
uc.mutation.SetCreatedAt(v)
}
if _, ok := uc.mutation.UpdatedAt(); !ok {
v := user.DefaultUpdatedAt()
uc.mutation.SetUpdatedAt(v)
}
if _, ok := uc.mutation.Next(); !ok {
v := user.DefaultNext
uc.mutation.SetNext(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (uc *UserCreate) check() error {
if _, ok := uc.mutation.Username(); !ok {
return &ValidationError{Name: "username", err: errors.New(`ent: missing required field "User.username"`)}
}
if v, ok := uc.mutation.Username(); ok {
if err := user.UsernameValidator(v); err != nil {
return &ValidationError{Name: "username", err: fmt.Errorf(`ent: validator failed for field "User.username": %w`, err)}
}
}
return nil
}
func (uc *UserCreate) sqlSave(ctx context.Context) (*User, error) {
if err := uc.check(); err != nil {
return nil, err
}
_node, _spec := uc.createSpec()
if err := sqlgraph.CreateNode(ctx, uc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
uc.mutation.id = &_node.ID
uc.mutation.done = true
return _node, nil
}
func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
var (
_node = &User{config: uc.config}
_spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
)
if value, ok := uc.mutation.Username(); ok {
_spec.SetField(user.FieldUsername, field.TypeString, value)
_node.Username = value
}
if value, ok := uc.mutation.CreatedAt(); ok {
_spec.SetField(user.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
if value, ok := uc.mutation.UpdatedAt(); ok {
_spec.SetField(user.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = value
}
if value, ok := uc.mutation.Next(); ok {
_spec.SetField(user.FieldNext, field.TypeString, value)
_node.Next = value
}
if nodes := uc.mutation.CardIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.CardTable,
Columns: []string{user.CardColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: card.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// UserCreateBulk is the builder for creating many User entities in bulk.
type UserCreateBulk struct {
config
builders []*UserCreate
}
// Save creates the User entities in the database.
func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) {
specs := make([]*sqlgraph.CreateSpec, len(ucb.builders))
nodes := make([]*User, len(ucb.builders))
mutators := make([]Mutator, len(ucb.builders))
for i := range ucb.builders {
func(i int, root context.Context) {
builder := ucb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*UserMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, ucb.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, ucb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, ucb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (ucb *UserCreateBulk) SaveX(ctx context.Context) []*User {
v, err := ucb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (ucb *UserCreateBulk) Exec(ctx context.Context) error {
_, err := ucb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ucb *UserCreateBulk) ExecX(ctx context.Context) {
if err := ucb.Exec(ctx); err != nil {
panic(err)
}
}

88
ent/user_delete.go Normal file
View File

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

611
ent/user_query.go Normal file
View File

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

467
ent/user_update.go Normal file
View File

@ -0,0 +1,467 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"t/ent/card"
"t/ent/predicate"
"t/ent/user"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UserUpdate is the builder for updating User entities.
type UserUpdate struct {
config
hooks []Hook
mutation *UserMutation
}
// Where appends a list predicates to the UserUpdate builder.
func (uu *UserUpdate) Where(ps ...predicate.User) *UserUpdate {
uu.mutation.Where(ps...)
return uu
}
// SetUpdatedAt sets the "updated_at" field.
func (uu *UserUpdate) SetUpdatedAt(t time.Time) *UserUpdate {
uu.mutation.SetUpdatedAt(t)
return uu
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (uu *UserUpdate) SetNillableUpdatedAt(t *time.Time) *UserUpdate {
if t != nil {
uu.SetUpdatedAt(*t)
}
return uu
}
// ClearUpdatedAt clears the value of the "updated_at" field.
func (uu *UserUpdate) ClearUpdatedAt() *UserUpdate {
uu.mutation.ClearUpdatedAt()
return uu
}
// SetNext sets the "next" field.
func (uu *UserUpdate) SetNext(s string) *UserUpdate {
uu.mutation.SetNext(s)
return uu
}
// SetNillableNext sets the "next" field if the given value is not nil.
func (uu *UserUpdate) SetNillableNext(s *string) *UserUpdate {
if s != nil {
uu.SetNext(*s)
}
return uu
}
// ClearNext clears the value of the "next" field.
func (uu *UserUpdate) ClearNext() *UserUpdate {
uu.mutation.ClearNext()
return uu
}
// AddCardIDs adds the "card" edge to the Card entity by IDs.
func (uu *UserUpdate) AddCardIDs(ids ...int) *UserUpdate {
uu.mutation.AddCardIDs(ids...)
return uu
}
// AddCard adds the "card" edges to the Card entity.
func (uu *UserUpdate) AddCard(c ...*Card) *UserUpdate {
ids := make([]int, len(c))
for i := range c {
ids[i] = c[i].ID
}
return uu.AddCardIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (uu *UserUpdate) Mutation() *UserMutation {
return uu.mutation
}
// ClearCard clears all "card" edges to the Card entity.
func (uu *UserUpdate) ClearCard() *UserUpdate {
uu.mutation.ClearCard()
return uu
}
// RemoveCardIDs removes the "card" edge to Card entities by IDs.
func (uu *UserUpdate) RemoveCardIDs(ids ...int) *UserUpdate {
uu.mutation.RemoveCardIDs(ids...)
return uu
}
// RemoveCard removes "card" edges to Card entities.
func (uu *UserUpdate) RemoveCard(c ...*Card) *UserUpdate {
ids := make([]int, len(c))
for i := range c {
ids[i] = c[i].ID
}
return uu.RemoveCardIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (uu *UserUpdate) Save(ctx context.Context) (int, error) {
return withHooks[int, UserMutation](ctx, uu.sqlSave, uu.mutation, uu.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (uu *UserUpdate) SaveX(ctx context.Context) int {
affected, err := uu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (uu *UserUpdate) Exec(ctx context.Context) error {
_, err := uu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (uu *UserUpdate) ExecX(ctx context.Context) {
if err := uu.Exec(ctx); err != nil {
panic(err)
}
}
func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
if ps := uu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if uu.mutation.CreatedAtCleared() {
_spec.ClearField(user.FieldCreatedAt, field.TypeTime)
}
if value, ok := uu.mutation.UpdatedAt(); ok {
_spec.SetField(user.FieldUpdatedAt, field.TypeTime, value)
}
if uu.mutation.UpdatedAtCleared() {
_spec.ClearField(user.FieldUpdatedAt, field.TypeTime)
}
if value, ok := uu.mutation.Next(); ok {
_spec.SetField(user.FieldNext, field.TypeString, value)
}
if uu.mutation.NextCleared() {
_spec.ClearField(user.FieldNext, field.TypeString)
}
if uu.mutation.CardCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.CardTable,
Columns: []string{user.CardColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: card.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := uu.mutation.RemovedCardIDs(); len(nodes) > 0 && !uu.mutation.CardCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.CardTable,
Columns: []string{user.CardColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: card.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := uu.mutation.CardIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.CardTable,
Columns: []string{user.CardColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: card.FieldID,
},
},
}
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, uu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{user.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
uu.mutation.done = true
return n, nil
}
// UserUpdateOne is the builder for updating a single User entity.
type UserUpdateOne struct {
config
fields []string
hooks []Hook
mutation *UserMutation
}
// SetUpdatedAt sets the "updated_at" field.
func (uuo *UserUpdateOne) SetUpdatedAt(t time.Time) *UserUpdateOne {
uuo.mutation.SetUpdatedAt(t)
return uuo
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (uuo *UserUpdateOne) SetNillableUpdatedAt(t *time.Time) *UserUpdateOne {
if t != nil {
uuo.SetUpdatedAt(*t)
}
return uuo
}
// ClearUpdatedAt clears the value of the "updated_at" field.
func (uuo *UserUpdateOne) ClearUpdatedAt() *UserUpdateOne {
uuo.mutation.ClearUpdatedAt()
return uuo
}
// SetNext sets the "next" field.
func (uuo *UserUpdateOne) SetNext(s string) *UserUpdateOne {
uuo.mutation.SetNext(s)
return uuo
}
// SetNillableNext sets the "next" field if the given value is not nil.
func (uuo *UserUpdateOne) SetNillableNext(s *string) *UserUpdateOne {
if s != nil {
uuo.SetNext(*s)
}
return uuo
}
// ClearNext clears the value of the "next" field.
func (uuo *UserUpdateOne) ClearNext() *UserUpdateOne {
uuo.mutation.ClearNext()
return uuo
}
// AddCardIDs adds the "card" edge to the Card entity by IDs.
func (uuo *UserUpdateOne) AddCardIDs(ids ...int) *UserUpdateOne {
uuo.mutation.AddCardIDs(ids...)
return uuo
}
// AddCard adds the "card" edges to the Card entity.
func (uuo *UserUpdateOne) AddCard(c ...*Card) *UserUpdateOne {
ids := make([]int, len(c))
for i := range c {
ids[i] = c[i].ID
}
return uuo.AddCardIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (uuo *UserUpdateOne) Mutation() *UserMutation {
return uuo.mutation
}
// ClearCard clears all "card" edges to the Card entity.
func (uuo *UserUpdateOne) ClearCard() *UserUpdateOne {
uuo.mutation.ClearCard()
return uuo
}
// RemoveCardIDs removes the "card" edge to Card entities by IDs.
func (uuo *UserUpdateOne) RemoveCardIDs(ids ...int) *UserUpdateOne {
uuo.mutation.RemoveCardIDs(ids...)
return uuo
}
// RemoveCard removes "card" edges to Card entities.
func (uuo *UserUpdateOne) RemoveCard(c ...*Card) *UserUpdateOne {
ids := make([]int, len(c))
for i := range c {
ids[i] = c[i].ID
}
return uuo.RemoveCardIDs(ids...)
}
// Where appends a list predicates to the UserUpdate builder.
func (uuo *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne {
uuo.mutation.Where(ps...)
return uuo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (uuo *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne {
uuo.fields = append([]string{field}, fields...)
return uuo
}
// Save executes the query and returns the updated User entity.
func (uuo *UserUpdateOne) Save(ctx context.Context) (*User, error) {
return withHooks[*User, UserMutation](ctx, uuo.sqlSave, uuo.mutation, uuo.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (uuo *UserUpdateOne) SaveX(ctx context.Context) *User {
node, err := uuo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (uuo *UserUpdateOne) Exec(ctx context.Context) error {
_, err := uuo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (uuo *UserUpdateOne) ExecX(ctx context.Context) {
if err := uuo.Exec(ctx); err != nil {
panic(err)
}
}
func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {
_spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
id, ok := uuo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "User.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := uuo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, user.FieldID)
for _, f := range fields {
if !user.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != user.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := uuo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if uuo.mutation.CreatedAtCleared() {
_spec.ClearField(user.FieldCreatedAt, field.TypeTime)
}
if value, ok := uuo.mutation.UpdatedAt(); ok {
_spec.SetField(user.FieldUpdatedAt, field.TypeTime, value)
}
if uuo.mutation.UpdatedAtCleared() {
_spec.ClearField(user.FieldUpdatedAt, field.TypeTime)
}
if value, ok := uuo.mutation.Next(); ok {
_spec.SetField(user.FieldNext, field.TypeString, value)
}
if uuo.mutation.NextCleared() {
_spec.ClearField(user.FieldNext, field.TypeString)
}
if uuo.mutation.CardCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.CardTable,
Columns: []string{user.CardColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: card.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := uuo.mutation.RemovedCardIDs(); len(nodes) > 0 && !uuo.mutation.CardCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.CardTable,
Columns: []string{user.CardColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: card.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := uuo.mutation.CardIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.CardTable,
Columns: []string{user.CardColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: card.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &User{config: uuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, uuo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{user.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
uuo.mutation.done = true
return _node, nil
}

View File

@ -1,276 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"t/ent/users"
"time"
"entgo.io/ent/dialect/sql"
)
// Users is the model entity for the Users schema.
type Users struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// User holds the value of the "user" field.
User string `json:"user,omitempty"`
// Chara holds the value of the "chara" field.
Chara string `json:"chara,omitempty"`
// Skill holds the value of the "skill" field.
Skill int `json:"skill,omitempty"`
// Hp holds the value of the "hp" field.
Hp int `json:"hp,omitempty"`
// Attack holds the value of the "attack" field.
Attack int `json:"attack,omitempty"`
// Defense holds the value of the "defense" field.
Defense int `json:"defense,omitempty"`
// Critical holds the value of the "critical" field.
Critical int `json:"critical,omitempty"`
// Battle holds the value of the "battle" field.
Battle int `json:"battle,omitempty"`
// Win holds the value of the "win" field.
Win int `json:"win,omitempty"`
// Day holds the value of the "day" field.
Day int `json:"day,omitempty"`
// Percentage holds the value of the "percentage" field.
Percentage float64 `json:"percentage,omitempty"`
// Limit holds the value of the "limit" field.
Limit bool `json:"limit,omitempty"`
// Status holds the value of the "status" field.
Status string `json:"status,omitempty"`
// Comment holds the value of the "comment" field.
Comment string `json:"comment,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// Next holds the value of the "next" field.
Next string `json:"next,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
// URL holds the value of the "url" field.
URL string `json:"url,omitempty"`
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Users) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case users.FieldLimit:
values[i] = new(sql.NullBool)
case users.FieldPercentage:
values[i] = new(sql.NullFloat64)
case users.FieldID, users.FieldSkill, users.FieldHp, users.FieldAttack, users.FieldDefense, users.FieldCritical, users.FieldBattle, users.FieldWin, users.FieldDay:
values[i] = new(sql.NullInt64)
case users.FieldUser, users.FieldChara, users.FieldStatus, users.FieldComment, users.FieldNext, users.FieldURL:
values[i] = new(sql.NullString)
case users.FieldCreatedAt, users.FieldUpdatedAt:
values[i] = new(sql.NullTime)
default:
return nil, fmt.Errorf("unexpected column %q for type Users", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Users fields.
func (u *Users) assignValues(columns []string, values []interface{}) 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 users.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
u.ID = int(value.Int64)
case users.FieldUser:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field user", values[i])
} else if value.Valid {
u.User = value.String
}
case users.FieldChara:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field chara", values[i])
} else if value.Valid {
u.Chara = value.String
}
case users.FieldSkill:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field skill", values[i])
} else if value.Valid {
u.Skill = int(value.Int64)
}
case users.FieldHp:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field hp", values[i])
} else if value.Valid {
u.Hp = int(value.Int64)
}
case users.FieldAttack:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field attack", values[i])
} else if value.Valid {
u.Attack = int(value.Int64)
}
case users.FieldDefense:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field defense", values[i])
} else if value.Valid {
u.Defense = int(value.Int64)
}
case users.FieldCritical:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field critical", values[i])
} else if value.Valid {
u.Critical = int(value.Int64)
}
case users.FieldBattle:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field battle", values[i])
} else if value.Valid {
u.Battle = int(value.Int64)
}
case users.FieldWin:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field win", values[i])
} else if value.Valid {
u.Win = int(value.Int64)
}
case users.FieldDay:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field day", values[i])
} else if value.Valid {
u.Day = int(value.Int64)
}
case users.FieldPercentage:
if value, ok := values[i].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field percentage", values[i])
} else if value.Valid {
u.Percentage = value.Float64
}
case users.FieldLimit:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field limit", values[i])
} else if value.Valid {
u.Limit = value.Bool
}
case users.FieldStatus:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field status", values[i])
} else if value.Valid {
u.Status = value.String
}
case users.FieldComment:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field comment", values[i])
} else if value.Valid {
u.Comment = value.String
}
case users.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 {
u.CreatedAt = value.Time
}
case users.FieldNext:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field next", values[i])
} else if value.Valid {
u.Next = value.String
}
case users.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 {
u.UpdatedAt = value.Time
}
case users.FieldURL:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field url", values[i])
} else if value.Valid {
u.URL = value.String
}
}
}
return nil
}
// Update returns a builder for updating this Users.
// Note that you need to call Users.Unwrap() before calling this method if this Users
// was returned from a transaction, and the transaction was committed or rolled back.
func (u *Users) Update() *UsersUpdateOne {
return (&UsersClient{config: u.config}).UpdateOne(u)
}
// Unwrap unwraps the Users 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 (u *Users) Unwrap() *Users {
tx, ok := u.config.driver.(*txDriver)
if !ok {
panic("ent: Users is not a transactional entity")
}
u.config.driver = tx.drv
return u
}
// String implements the fmt.Stringer.
func (u *Users) String() string {
var builder strings.Builder
builder.WriteString("Users(")
builder.WriteString(fmt.Sprintf("id=%v", u.ID))
builder.WriteString(", user=")
builder.WriteString(u.User)
builder.WriteString(", chara=")
builder.WriteString(u.Chara)
builder.WriteString(", skill=")
builder.WriteString(fmt.Sprintf("%v", u.Skill))
builder.WriteString(", hp=")
builder.WriteString(fmt.Sprintf("%v", u.Hp))
builder.WriteString(", attack=")
builder.WriteString(fmt.Sprintf("%v", u.Attack))
builder.WriteString(", defense=")
builder.WriteString(fmt.Sprintf("%v", u.Defense))
builder.WriteString(", critical=")
builder.WriteString(fmt.Sprintf("%v", u.Critical))
builder.WriteString(", battle=")
builder.WriteString(fmt.Sprintf("%v", u.Battle))
builder.WriteString(", win=")
builder.WriteString(fmt.Sprintf("%v", u.Win))
builder.WriteString(", day=")
builder.WriteString(fmt.Sprintf("%v", u.Day))
builder.WriteString(", percentage=")
builder.WriteString(fmt.Sprintf("%v", u.Percentage))
builder.WriteString(", limit=")
builder.WriteString(fmt.Sprintf("%v", u.Limit))
builder.WriteString(", status=")
builder.WriteString(u.Status)
builder.WriteString(", comment=")
builder.WriteString(u.Comment)
builder.WriteString(", created_at=")
builder.WriteString(u.CreatedAt.Format(time.ANSIC))
builder.WriteString(", next=")
builder.WriteString(u.Next)
builder.WriteString(", updated_at=")
builder.WriteString(u.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", url=")
builder.WriteString(u.URL)
builder.WriteByte(')')
return builder.String()
}
// UsersSlice is a parsable slice of Users.
type UsersSlice []*Users
func (u UsersSlice) config(cfg config) {
for _i := range u {
u[_i].config = cfg
}
}

View File

@ -1,124 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package users
import (
"time"
)
const (
// Label holds the string label denoting the users type in the database.
Label = "users"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldUser holds the string denoting the user field in the database.
FieldUser = "user"
// FieldChara holds the string denoting the chara field in the database.
FieldChara = "chara"
// FieldSkill holds the string denoting the skill field in the database.
FieldSkill = "skill"
// FieldHp holds the string denoting the hp field in the database.
FieldHp = "hp"
// FieldAttack holds the string denoting the attack field in the database.
FieldAttack = "attack"
// FieldDefense holds the string denoting the defense field in the database.
FieldDefense = "defense"
// FieldCritical holds the string denoting the critical field in the database.
FieldCritical = "critical"
// FieldBattle holds the string denoting the battle field in the database.
FieldBattle = "battle"
// FieldWin holds the string denoting the win field in the database.
FieldWin = "win"
// FieldDay holds the string denoting the day field in the database.
FieldDay = "day"
// FieldPercentage holds the string denoting the percentage field in the database.
FieldPercentage = "percentage"
// FieldLimit holds the string denoting the limit field in the database.
FieldLimit = "limit"
// FieldStatus holds the string denoting the status field in the database.
FieldStatus = "status"
// FieldComment holds the string denoting the comment field in the database.
FieldComment = "comment"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldNext holds the string denoting the next field in the database.
FieldNext = "next"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// FieldURL holds the string denoting the url field in the database.
FieldURL = "url"
// Table holds the table name of the users in the database.
Table = "users"
)
// Columns holds all SQL columns for users fields.
var Columns = []string{
FieldID,
FieldUser,
FieldChara,
FieldSkill,
FieldHp,
FieldAttack,
FieldDefense,
FieldCritical,
FieldBattle,
FieldWin,
FieldDay,
FieldPercentage,
FieldLimit,
FieldStatus,
FieldComment,
FieldCreatedAt,
FieldNext,
FieldUpdatedAt,
FieldURL,
}
// 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 (
// UserValidator is a validator for the "user" field. It is called by the builders before save.
UserValidator func(string) error
// DefaultChara holds the default value on creation for the "chara" field.
DefaultChara string
// DefaultSkill holds the default value on creation for the "skill" field.
DefaultSkill int
// DefaultHp holds the default value on creation for the "hp" field.
DefaultHp int
// DefaultAttack holds the default value on creation for the "attack" field.
DefaultAttack int
// DefaultDefense holds the default value on creation for the "defense" field.
DefaultDefense int
// DefaultCritical holds the default value on creation for the "critical" field.
DefaultCritical int
// DefaultBattle holds the default value on creation for the "battle" field.
DefaultBattle int
// DefaultWin holds the default value on creation for the "win" field.
DefaultWin int
// DefaultDay holds the default value on creation for the "day" field.
DefaultDay int
// DefaultPercentage holds the default value on creation for the "percentage" field.
DefaultPercentage float64
// DefaultLimit holds the default value on creation for the "limit" field.
DefaultLimit bool
// DefaultStatus holds the default value on creation for the "status" field.
DefaultStatus string
// DefaultComment holds the default value on creation for the "comment" field.
DefaultComment string
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultNext holds the default value on creation for the "next" field.
DefaultNext string
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// DefaultURL holds the default value on creation for the "url" field.
DefaultURL string
)

File diff suppressed because it is too large Load Diff

View File

@ -1,674 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"t/ent/users"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UsersCreate is the builder for creating a Users entity.
type UsersCreate struct {
config
mutation *UsersMutation
hooks []Hook
}
// SetUser sets the "user" field.
func (uc *UsersCreate) SetUser(s string) *UsersCreate {
uc.mutation.SetUser(s)
return uc
}
// SetChara sets the "chara" field.
func (uc *UsersCreate) SetChara(s string) *UsersCreate {
uc.mutation.SetChara(s)
return uc
}
// SetNillableChara sets the "chara" field if the given value is not nil.
func (uc *UsersCreate) SetNillableChara(s *string) *UsersCreate {
if s != nil {
uc.SetChara(*s)
}
return uc
}
// SetSkill sets the "skill" field.
func (uc *UsersCreate) SetSkill(i int) *UsersCreate {
uc.mutation.SetSkill(i)
return uc
}
// SetNillableSkill sets the "skill" field if the given value is not nil.
func (uc *UsersCreate) SetNillableSkill(i *int) *UsersCreate {
if i != nil {
uc.SetSkill(*i)
}
return uc
}
// SetHp sets the "hp" field.
func (uc *UsersCreate) SetHp(i int) *UsersCreate {
uc.mutation.SetHp(i)
return uc
}
// SetNillableHp sets the "hp" field if the given value is not nil.
func (uc *UsersCreate) SetNillableHp(i *int) *UsersCreate {
if i != nil {
uc.SetHp(*i)
}
return uc
}
// SetAttack sets the "attack" field.
func (uc *UsersCreate) SetAttack(i int) *UsersCreate {
uc.mutation.SetAttack(i)
return uc
}
// SetNillableAttack sets the "attack" field if the given value is not nil.
func (uc *UsersCreate) SetNillableAttack(i *int) *UsersCreate {
if i != nil {
uc.SetAttack(*i)
}
return uc
}
// SetDefense sets the "defense" field.
func (uc *UsersCreate) SetDefense(i int) *UsersCreate {
uc.mutation.SetDefense(i)
return uc
}
// SetNillableDefense sets the "defense" field if the given value is not nil.
func (uc *UsersCreate) SetNillableDefense(i *int) *UsersCreate {
if i != nil {
uc.SetDefense(*i)
}
return uc
}
// SetCritical sets the "critical" field.
func (uc *UsersCreate) SetCritical(i int) *UsersCreate {
uc.mutation.SetCritical(i)
return uc
}
// SetNillableCritical sets the "critical" field if the given value is not nil.
func (uc *UsersCreate) SetNillableCritical(i *int) *UsersCreate {
if i != nil {
uc.SetCritical(*i)
}
return uc
}
// SetBattle sets the "battle" field.
func (uc *UsersCreate) SetBattle(i int) *UsersCreate {
uc.mutation.SetBattle(i)
return uc
}
// SetNillableBattle sets the "battle" field if the given value is not nil.
func (uc *UsersCreate) SetNillableBattle(i *int) *UsersCreate {
if i != nil {
uc.SetBattle(*i)
}
return uc
}
// SetWin sets the "win" field.
func (uc *UsersCreate) SetWin(i int) *UsersCreate {
uc.mutation.SetWin(i)
return uc
}
// SetNillableWin sets the "win" field if the given value is not nil.
func (uc *UsersCreate) SetNillableWin(i *int) *UsersCreate {
if i != nil {
uc.SetWin(*i)
}
return uc
}
// SetDay sets the "day" field.
func (uc *UsersCreate) SetDay(i int) *UsersCreate {
uc.mutation.SetDay(i)
return uc
}
// SetNillableDay sets the "day" field if the given value is not nil.
func (uc *UsersCreate) SetNillableDay(i *int) *UsersCreate {
if i != nil {
uc.SetDay(*i)
}
return uc
}
// SetPercentage sets the "percentage" field.
func (uc *UsersCreate) SetPercentage(f float64) *UsersCreate {
uc.mutation.SetPercentage(f)
return uc
}
// SetNillablePercentage sets the "percentage" field if the given value is not nil.
func (uc *UsersCreate) SetNillablePercentage(f *float64) *UsersCreate {
if f != nil {
uc.SetPercentage(*f)
}
return uc
}
// SetLimit sets the "limit" field.
func (uc *UsersCreate) SetLimit(b bool) *UsersCreate {
uc.mutation.SetLimit(b)
return uc
}
// SetNillableLimit sets the "limit" field if the given value is not nil.
func (uc *UsersCreate) SetNillableLimit(b *bool) *UsersCreate {
if b != nil {
uc.SetLimit(*b)
}
return uc
}
// SetStatus sets the "status" field.
func (uc *UsersCreate) SetStatus(s string) *UsersCreate {
uc.mutation.SetStatus(s)
return uc
}
// SetNillableStatus sets the "status" field if the given value is not nil.
func (uc *UsersCreate) SetNillableStatus(s *string) *UsersCreate {
if s != nil {
uc.SetStatus(*s)
}
return uc
}
// SetComment sets the "comment" field.
func (uc *UsersCreate) SetComment(s string) *UsersCreate {
uc.mutation.SetComment(s)
return uc
}
// SetNillableComment sets the "comment" field if the given value is not nil.
func (uc *UsersCreate) SetNillableComment(s *string) *UsersCreate {
if s != nil {
uc.SetComment(*s)
}
return uc
}
// SetCreatedAt sets the "created_at" field.
func (uc *UsersCreate) SetCreatedAt(t time.Time) *UsersCreate {
uc.mutation.SetCreatedAt(t)
return uc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (uc *UsersCreate) SetNillableCreatedAt(t *time.Time) *UsersCreate {
if t != nil {
uc.SetCreatedAt(*t)
}
return uc
}
// SetNext sets the "next" field.
func (uc *UsersCreate) SetNext(s string) *UsersCreate {
uc.mutation.SetNext(s)
return uc
}
// SetNillableNext sets the "next" field if the given value is not nil.
func (uc *UsersCreate) SetNillableNext(s *string) *UsersCreate {
if s != nil {
uc.SetNext(*s)
}
return uc
}
// SetUpdatedAt sets the "updated_at" field.
func (uc *UsersCreate) SetUpdatedAt(t time.Time) *UsersCreate {
uc.mutation.SetUpdatedAt(t)
return uc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (uc *UsersCreate) SetNillableUpdatedAt(t *time.Time) *UsersCreate {
if t != nil {
uc.SetUpdatedAt(*t)
}
return uc
}
// SetURL sets the "url" field.
func (uc *UsersCreate) SetURL(s string) *UsersCreate {
uc.mutation.SetURL(s)
return uc
}
// SetNillableURL sets the "url" field if the given value is not nil.
func (uc *UsersCreate) SetNillableURL(s *string) *UsersCreate {
if s != nil {
uc.SetURL(*s)
}
return uc
}
// Mutation returns the UsersMutation object of the builder.
func (uc *UsersCreate) Mutation() *UsersMutation {
return uc.mutation
}
// Save creates the Users in the database.
func (uc *UsersCreate) Save(ctx context.Context) (*Users, error) {
var (
err error
node *Users
)
uc.defaults()
if len(uc.hooks) == 0 {
if err = uc.check(); err != nil {
return nil, err
}
node, err = uc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*UsersMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = uc.check(); err != nil {
return nil, err
}
uc.mutation = mutation
if node, err = uc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(uc.hooks) - 1; i >= 0; i-- {
if uc.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = uc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, uc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (uc *UsersCreate) SaveX(ctx context.Context) *Users {
v, err := uc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (uc *UsersCreate) Exec(ctx context.Context) error {
_, err := uc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (uc *UsersCreate) ExecX(ctx context.Context) {
if err := uc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (uc *UsersCreate) defaults() {
if _, ok := uc.mutation.Chara(); !ok {
v := users.DefaultChara
uc.mutation.SetChara(v)
}
if _, ok := uc.mutation.Skill(); !ok {
v := users.DefaultSkill
uc.mutation.SetSkill(v)
}
if _, ok := uc.mutation.Hp(); !ok {
v := users.DefaultHp
uc.mutation.SetHp(v)
}
if _, ok := uc.mutation.Attack(); !ok {
v := users.DefaultAttack
uc.mutation.SetAttack(v)
}
if _, ok := uc.mutation.Defense(); !ok {
v := users.DefaultDefense
uc.mutation.SetDefense(v)
}
if _, ok := uc.mutation.Critical(); !ok {
v := users.DefaultCritical
uc.mutation.SetCritical(v)
}
if _, ok := uc.mutation.Battle(); !ok {
v := users.DefaultBattle
uc.mutation.SetBattle(v)
}
if _, ok := uc.mutation.Win(); !ok {
v := users.DefaultWin
uc.mutation.SetWin(v)
}
if _, ok := uc.mutation.Day(); !ok {
v := users.DefaultDay
uc.mutation.SetDay(v)
}
if _, ok := uc.mutation.Percentage(); !ok {
v := users.DefaultPercentage
uc.mutation.SetPercentage(v)
}
if _, ok := uc.mutation.Limit(); !ok {
v := users.DefaultLimit
uc.mutation.SetLimit(v)
}
if _, ok := uc.mutation.Status(); !ok {
v := users.DefaultStatus
uc.mutation.SetStatus(v)
}
if _, ok := uc.mutation.Comment(); !ok {
v := users.DefaultComment
uc.mutation.SetComment(v)
}
if _, ok := uc.mutation.CreatedAt(); !ok {
v := users.DefaultCreatedAt()
uc.mutation.SetCreatedAt(v)
}
if _, ok := uc.mutation.Next(); !ok {
v := users.DefaultNext
uc.mutation.SetNext(v)
}
if _, ok := uc.mutation.UpdatedAt(); !ok {
v := users.DefaultUpdatedAt()
uc.mutation.SetUpdatedAt(v)
}
if _, ok := uc.mutation.URL(); !ok {
v := users.DefaultURL
uc.mutation.SetURL(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (uc *UsersCreate) check() error {
if _, ok := uc.mutation.User(); !ok {
return &ValidationError{Name: "user", err: errors.New(`ent: missing required field "Users.user"`)}
}
if v, ok := uc.mutation.User(); ok {
if err := users.UserValidator(v); err != nil {
return &ValidationError{Name: "user", err: fmt.Errorf(`ent: validator failed for field "Users.user": %w`, err)}
}
}
return nil
}
func (uc *UsersCreate) sqlSave(ctx context.Context) (*Users, error) {
_node, _spec := uc.createSpec()
if err := sqlgraph.CreateNode(ctx, uc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
return _node, nil
}
func (uc *UsersCreate) createSpec() (*Users, *sqlgraph.CreateSpec) {
var (
_node = &Users{config: uc.config}
_spec = &sqlgraph.CreateSpec{
Table: users.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: users.FieldID,
},
}
)
if value, ok := uc.mutation.User(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: users.FieldUser,
})
_node.User = value
}
if value, ok := uc.mutation.Chara(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: users.FieldChara,
})
_node.Chara = value
}
if value, ok := uc.mutation.Skill(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: users.FieldSkill,
})
_node.Skill = value
}
if value, ok := uc.mutation.Hp(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: users.FieldHp,
})
_node.Hp = value
}
if value, ok := uc.mutation.Attack(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: users.FieldAttack,
})
_node.Attack = value
}
if value, ok := uc.mutation.Defense(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: users.FieldDefense,
})
_node.Defense = value
}
if value, ok := uc.mutation.Critical(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: users.FieldCritical,
})
_node.Critical = value
}
if value, ok := uc.mutation.Battle(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: users.FieldBattle,
})
_node.Battle = value
}
if value, ok := uc.mutation.Win(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: users.FieldWin,
})
_node.Win = value
}
if value, ok := uc.mutation.Day(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: users.FieldDay,
})
_node.Day = value
}
if value, ok := uc.mutation.Percentage(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeFloat64,
Value: value,
Column: users.FieldPercentage,
})
_node.Percentage = value
}
if value, ok := uc.mutation.Limit(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: users.FieldLimit,
})
_node.Limit = value
}
if value, ok := uc.mutation.Status(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: users.FieldStatus,
})
_node.Status = value
}
if value, ok := uc.mutation.Comment(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: users.FieldComment,
})
_node.Comment = value
}
if value, ok := uc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: users.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := uc.mutation.Next(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: users.FieldNext,
})
_node.Next = value
}
if value, ok := uc.mutation.UpdatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: users.FieldUpdatedAt,
})
_node.UpdatedAt = value
}
if value, ok := uc.mutation.URL(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: users.FieldURL,
})
_node.URL = value
}
return _node, _spec
}
// UsersCreateBulk is the builder for creating many Users entities in bulk.
type UsersCreateBulk struct {
config
builders []*UsersCreate
}
// Save creates the Users entities in the database.
func (ucb *UsersCreateBulk) Save(ctx context.Context) ([]*Users, error) {
specs := make([]*sqlgraph.CreateSpec, len(ucb.builders))
nodes := make([]*Users, len(ucb.builders))
mutators := make([]Mutator, len(ucb.builders))
for i := range ucb.builders {
func(i int, root context.Context) {
builder := ucb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*UsersMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, ucb.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, ucb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
mutation.done = true
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
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, ucb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (ucb *UsersCreateBulk) SaveX(ctx context.Context) []*Users {
v, err := ucb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (ucb *UsersCreateBulk) Exec(ctx context.Context) error {
_, err := ucb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ucb *UsersCreateBulk) ExecX(ctx context.Context) {
if err := ucb.Exec(ctx); err != nil {
panic(err)
}
}

View File

@ -1,111 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"t/ent/predicate"
"t/ent/users"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UsersDelete is the builder for deleting a Users entity.
type UsersDelete struct {
config
hooks []Hook
mutation *UsersMutation
}
// Where appends a list predicates to the UsersDelete builder.
func (ud *UsersDelete) Where(ps ...predicate.Users) *UsersDelete {
ud.mutation.Where(ps...)
return ud
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (ud *UsersDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(ud.hooks) == 0 {
affected, err = ud.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*UsersMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
ud.mutation = mutation
affected, err = ud.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(ud.hooks) - 1; i >= 0; i-- {
if ud.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = ud.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, ud.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (ud *UsersDelete) ExecX(ctx context.Context) int {
n, err := ud.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (ud *UsersDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: users.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: users.FieldID,
},
},
}
if ps := ud.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return sqlgraph.DeleteNodes(ctx, ud.driver, _spec)
}
// UsersDeleteOne is the builder for deleting a single Users entity.
type UsersDeleteOne struct {
ud *UsersDelete
}
// Exec executes the deletion query.
func (udo *UsersDeleteOne) Exec(ctx context.Context) error {
n, err := udo.ud.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{users.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (udo *UsersDeleteOne) ExecX(ctx context.Context) {
udo.ud.ExecX(ctx)
}

View File

@ -1,920 +0,0 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"math"
"t/ent/predicate"
"t/ent/users"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UsersQuery is the builder for querying Users entities.
type UsersQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.Users
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the UsersQuery builder.
func (uq *UsersQuery) Where(ps ...predicate.Users) *UsersQuery {
uq.predicates = append(uq.predicates, ps...)
return uq
}
// Limit adds a limit step to the query.
func (uq *UsersQuery) Limit(limit int) *UsersQuery {
uq.limit = &limit
return uq
}
// Offset adds an offset step to the query.
func (uq *UsersQuery) Offset(offset int) *UsersQuery {
uq.offset = &offset
return uq
}
// 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 (uq *UsersQuery) Unique(unique bool) *UsersQuery {
uq.unique = &unique
return uq
}
// Order adds an order step to the query.
func (uq *UsersQuery) Order(o ...OrderFunc) *UsersQuery {
uq.order = append(uq.order, o...)
return uq
}
// First returns the first Users entity from the query.
// Returns a *NotFoundError when no Users was found.
func (uq *UsersQuery) First(ctx context.Context) (*Users, error) {
nodes, err := uq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{users.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (uq *UsersQuery) FirstX(ctx context.Context) *Users {
node, err := uq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Users ID from the query.
// Returns a *NotFoundError when no Users ID was found.
func (uq *UsersQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = uq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{users.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (uq *UsersQuery) FirstIDX(ctx context.Context) int {
id, err := uq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Users entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when exactly one Users entity is not found.
// Returns a *NotFoundError when no Users entities are found.
func (uq *UsersQuery) Only(ctx context.Context) (*Users, error) {
nodes, err := uq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{users.Label}
default:
return nil, &NotSingularError{users.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (uq *UsersQuery) OnlyX(ctx context.Context) *Users {
node, err := uq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Users ID in the query.
// Returns a *NotSingularError when exactly one Users ID is not found.
// Returns a *NotFoundError when no entities are found.
func (uq *UsersQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = uq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{users.Label}
default:
err = &NotSingularError{users.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (uq *UsersQuery) OnlyIDX(ctx context.Context) int {
id, err := uq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of UsersSlice.
func (uq *UsersQuery) All(ctx context.Context) ([]*Users, error) {
if err := uq.prepareQuery(ctx); err != nil {
return nil, err
}
return uq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (uq *UsersQuery) AllX(ctx context.Context) []*Users {
nodes, err := uq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Users IDs.
func (uq *UsersQuery) IDs(ctx context.Context) ([]int, error) {
var ids []int
if err := uq.Select(users.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (uq *UsersQuery) IDsX(ctx context.Context) []int {
ids, err := uq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (uq *UsersQuery) Count(ctx context.Context) (int, error) {
if err := uq.prepareQuery(ctx); err != nil {
return 0, err
}
return uq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (uq *UsersQuery) CountX(ctx context.Context) int {
count, err := uq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (uq *UsersQuery) Exist(ctx context.Context) (bool, error) {
if err := uq.prepareQuery(ctx); err != nil {
return false, err
}
return uq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (uq *UsersQuery) ExistX(ctx context.Context) bool {
exist, err := uq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the UsersQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (uq *UsersQuery) Clone() *UsersQuery {
if uq == nil {
return nil
}
return &UsersQuery{
config: uq.config,
limit: uq.limit,
offset: uq.offset,
order: append([]OrderFunc{}, uq.order...),
predicates: append([]predicate.Users{}, uq.predicates...),
// clone intermediate query.
sql: uq.sql.Clone(),
path: uq.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// User string `json:"user,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Users.Query().
// GroupBy(users.FieldUser).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
//
func (uq *UsersQuery) GroupBy(field string, fields ...string) *UsersGroupBy {
group := &UsersGroupBy{config: uq.config}
group.fields = append([]string{field}, fields...)
group.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := uq.prepareQuery(ctx); err != nil {
return nil, err
}
return uq.sqlQuery(ctx), nil
}
return group
}
// 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 {
// User string `json:"user,omitempty"`
// }
//
// client.Users.Query().
// Select(users.FieldUser).
// Scan(ctx, &v)
//
func (uq *UsersQuery) Select(fields ...string) *UsersSelect {
uq.fields = append(uq.fields, fields...)
return &UsersSelect{UsersQuery: uq}
}
func (uq *UsersQuery) prepareQuery(ctx context.Context) error {
for _, f := range uq.fields {
if !users.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if uq.path != nil {
prev, err := uq.path(ctx)
if err != nil {
return err
}
uq.sql = prev
}
return nil
}
func (uq *UsersQuery) sqlAll(ctx context.Context) ([]*Users, error) {
var (
nodes = []*Users{}
_spec = uq.querySpec()
)
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
node := &Users{config: uq.config}
nodes = append(nodes, node)
return node.scanValues(columns)
}
_spec.Assign = func(columns []string, values []interface{}) error {
if len(nodes) == 0 {
return fmt.Errorf("ent: Assign called without calling ScanValues")
}
node := nodes[len(nodes)-1]
return node.assignValues(columns, values)
}
if err := sqlgraph.QueryNodes(ctx, uq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (uq *UsersQuery) sqlCount(ctx context.Context) (int, error) {
_spec := uq.querySpec()
_spec.Node.Columns = uq.fields
if len(uq.fields) > 0 {
_spec.Unique = uq.unique != nil && *uq.unique
}
return sqlgraph.CountNodes(ctx, uq.driver, _spec)
}
func (uq *UsersQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := uq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("ent: check existence: %w", err)
}
return n > 0, nil
}
func (uq *UsersQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: users.Table,
Columns: users.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: users.FieldID,
},
},
From: uq.sql,
Unique: true,
}
if unique := uq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := uq.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, users.FieldID)
for i := range fields {
if fields[i] != users.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := uq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := uq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := uq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := uq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (uq *UsersQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(uq.driver.Dialect())
t1 := builder.Table(users.Table)
columns := uq.fields
if len(columns) == 0 {
columns = users.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if uq.sql != nil {
selector = uq.sql
selector.Select(selector.Columns(columns...)...)
}
if uq.unique != nil && *uq.unique {
selector.Distinct()
}
for _, p := range uq.predicates {
p(selector)
}
for _, p := range uq.order {
p(selector)
}
if offset := uq.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 := uq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// UsersGroupBy is the group-by builder for Users entities.
type UsersGroupBy struct {
config
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (ugb *UsersGroupBy) Aggregate(fns ...AggregateFunc) *UsersGroupBy {
ugb.fns = append(ugb.fns, fns...)
return ugb
}
// Scan applies the group-by query and scans the result into the given value.
func (ugb *UsersGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := ugb.path(ctx)
if err != nil {
return err
}
ugb.sql = query
return ugb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (ugb *UsersGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := ugb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by.
// It is only allowed when executing a group-by query with one field.
func (ugb *UsersGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(ugb.fields) > 1 {
return nil, errors.New("ent: UsersGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := ugb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (ugb *UsersGroupBy) StringsX(ctx context.Context) []string {
v, err := ugb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (ugb *UsersGroupBy) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = ugb.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{users.Label}
default:
err = fmt.Errorf("ent: UsersGroupBy.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (ugb *UsersGroupBy) StringX(ctx context.Context) string {
v, err := ugb.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by.
// It is only allowed when executing a group-by query with one field.
func (ugb *UsersGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(ugb.fields) > 1 {
return nil, errors.New("ent: UsersGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := ugb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (ugb *UsersGroupBy) IntsX(ctx context.Context) []int {
v, err := ugb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (ugb *UsersGroupBy) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = ugb.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{users.Label}
default:
err = fmt.Errorf("ent: UsersGroupBy.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (ugb *UsersGroupBy) IntX(ctx context.Context) int {
v, err := ugb.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by.
// It is only allowed when executing a group-by query with one field.
func (ugb *UsersGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(ugb.fields) > 1 {
return nil, errors.New("ent: UsersGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := ugb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (ugb *UsersGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := ugb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (ugb *UsersGroupBy) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = ugb.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{users.Label}
default:
err = fmt.Errorf("ent: UsersGroupBy.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (ugb *UsersGroupBy) Float64X(ctx context.Context) float64 {
v, err := ugb.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by.
// It is only allowed when executing a group-by query with one field.
func (ugb *UsersGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(ugb.fields) > 1 {
return nil, errors.New("ent: UsersGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := ugb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (ugb *UsersGroupBy) BoolsX(ctx context.Context) []bool {
v, err := ugb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (ugb *UsersGroupBy) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = ugb.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{users.Label}
default:
err = fmt.Errorf("ent: UsersGroupBy.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (ugb *UsersGroupBy) BoolX(ctx context.Context) bool {
v, err := ugb.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (ugb *UsersGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range ugb.fields {
if !users.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := ugb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := ugb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (ugb *UsersGroupBy) sqlQuery() *sql.Selector {
selector := ugb.sql.Select()
aggregation := make([]string, 0, len(ugb.fns))
for _, fn := range ugb.fns {
aggregation = append(aggregation, fn(selector))
}
// If no columns were selected in a custom aggregation function, the default
// selection is the fields used for "group-by", and the aggregation functions.
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(ugb.fields)+len(ugb.fns))
for _, f := range ugb.fields {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
return selector.GroupBy(selector.Columns(ugb.fields...)...)
}
// UsersSelect is the builder for selecting fields of Users entities.
type UsersSelect struct {
*UsersQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (us *UsersSelect) Scan(ctx context.Context, v interface{}) error {
if err := us.prepareQuery(ctx); err != nil {
return err
}
us.sql = us.UsersQuery.sqlQuery(ctx)
return us.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (us *UsersSelect) ScanX(ctx context.Context, v interface{}) {
if err := us.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (us *UsersSelect) Strings(ctx context.Context) ([]string, error) {
if len(us.fields) > 1 {
return nil, errors.New("ent: UsersSelect.Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := us.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (us *UsersSelect) StringsX(ctx context.Context) []string {
v, err := us.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 (us *UsersSelect) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = us.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{users.Label}
default:
err = fmt.Errorf("ent: UsersSelect.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (us *UsersSelect) StringX(ctx context.Context) string {
v, err := us.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 (us *UsersSelect) Ints(ctx context.Context) ([]int, error) {
if len(us.fields) > 1 {
return nil, errors.New("ent: UsersSelect.Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := us.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (us *UsersSelect) IntsX(ctx context.Context) []int {
v, err := us.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 (us *UsersSelect) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = us.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{users.Label}
default:
err = fmt.Errorf("ent: UsersSelect.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (us *UsersSelect) IntX(ctx context.Context) int {
v, err := us.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 (us *UsersSelect) Float64s(ctx context.Context) ([]float64, error) {
if len(us.fields) > 1 {
return nil, errors.New("ent: UsersSelect.Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := us.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (us *UsersSelect) Float64sX(ctx context.Context) []float64 {
v, err := us.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 (us *UsersSelect) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = us.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{users.Label}
default:
err = fmt.Errorf("ent: UsersSelect.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (us *UsersSelect) Float64X(ctx context.Context) float64 {
v, err := us.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 (us *UsersSelect) Bools(ctx context.Context) ([]bool, error) {
if len(us.fields) > 1 {
return nil, errors.New("ent: UsersSelect.Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := us.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (us *UsersSelect) BoolsX(ctx context.Context) []bool {
v, err := us.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 (us *UsersSelect) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = us.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{users.Label}
default:
err = fmt.Errorf("ent: UsersSelect.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (us *UsersSelect) BoolX(ctx context.Context) bool {
v, err := us.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (us *UsersSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := us.sql.Query()
if err := us.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

File diff suppressed because it is too large Load Diff

View File

@ -1,29 +0,0 @@
# fly.toml file generated for ent on 2022-08-31T13:39:30+09:00
app = "ent"
kill_signal = "SIGINT"
kill_timeout = 5
[build]
builder = "paketobuildpacks/builder:base"
buildpacks = ["gcr.io/paketo-buildpacks/go"]
[env]
PORT = "8080"
[processes]
api = "bin/t"
[[services]]
internal_port = 8080
processes = ["api"]
protocol = "tcp"
[[services.ports]]
force_https = true
handlers = ["http"]
port = 80
[[services.ports]]
handlers = ["tls", "http"]
port = 443

85
go.mod
View File

@ -1,59 +1,56 @@
module t
// +heroku goVersion go1.17
go 1.17
go 1.19
//replace ariga.io/ogent => ../../
require (
entgo.io/ent v0.10.0
github.com/go-chi/chi/v5 v5.0.4
github.com/jackc/pgx/v4 v4.15.0
github.com/lib/pq v1.10.4
github.com/mailru/easyjson v0.7.7
go.uber.org/zap v1.21.0
entgo.io/ent v0.11.9
github.com/go-faster/errors v0.6.1
github.com/go-faster/jx v0.42.0-alpha.1
github.com/mattn/go-sqlite3 v1.14.16
github.com/mazen160/go-random v0.0.0-20210308102632-d2b501c85c03
github.com/ogen-go/ogen v0.59.0
go.opentelemetry.io/otel v1.13.0
go.opentelemetry.io/otel/metric v0.36.0
go.opentelemetry.io/otel/trace v1.13.0
go.uber.org/multierr v1.9.0
)
require (
entgo.io/contrib v0.2.1-0.20220210075301-2b75bf138815 // indirect
ariga.io/atlas v0.9.1 // indirect
ariga.io/entviz v0.0.0-20230125130633-6c9be8e08c7c // indirect
ariga.io/ogent v0.0.0-20230309073626-8dc564a6a73e // indirect
entgo.io/contrib v0.3.5 // indirect
github.com/agext/levenshtein v1.2.3 // indirect
github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect
github.com/ariga/ogent v0.0.0-20220224071349-f1dbffa2e32a // indirect
github.com/dlclark/regexp2 v1.8.0 // indirect
github.com/fatih/color v1.14.1 // indirect
github.com/ghodss/yaml v1.0.0 // indirect
github.com/go-logr/logr v1.2.2 // indirect
github.com/go-faster/yamlx v0.4.1 // indirect
github.com/go-logr/logr v1.2.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-openapi/inflect v0.19.0 // indirect
github.com/golang/mock v1.6.0 // indirect
github.com/google/go-cmp v0.5.7 // indirect
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgconn v1.11.0 // indirect
github.com/jackc/pgio v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgproto3/v2 v2.2.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
github.com/jackc/pgtype v1.10.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/google/go-cmp v0.5.9 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/hashicorp/hcl/v2 v2.15.0 // indirect
github.com/kyokomi/lottery v1.2.0 // indirect
github.com/segmentio/asm v1.1.3 // indirect
github.com/uniplaces/carbon v0.1.6 // indirect
golang.org/x/crypto v0.0.0-20220112180741-5e0467b6c7ce // indirect
golang.org/x/mod v0.5.1 // indirect
golang.org/x/text v0.3.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/mitchellh/go-wordwrap v1.0.1 // indirect
github.com/segmentio/asm v1.2.0 // indirect
github.com/sergi/go-diff v1.1.0 // indirect
github.com/stoewer/go-strcase v1.2.0 // indirect
github.com/zclconf/go-cty v1.12.1 // indirect
go.uber.org/atomic v1.10.0 // indirect
go.uber.org/zap v1.24.0 // indirect
golang.org/x/exp v0.0.0-20230206171751-46f607a40771 // indirect
golang.org/x/mod v0.8.0 // indirect
golang.org/x/net v0.7.0 // indirect
golang.org/x/sync v0.1.0 // indirect
golang.org/x/sys v0.5.0 // indirect
golang.org/x/text v0.7.0 // indirect
golang.org/x/tools v0.6.1-0.20230222164832-25d2519c8696 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
require (
ariga.io/atlas v0.3.5 // indirect
github.com/agext/levenshtein v1.2.3 // indirect
github.com/go-faster/errors v0.5.0
github.com/go-faster/jx v0.32.2
github.com/google/uuid v1.3.0
github.com/hashicorp/hcl/v2 v2.11.1 // indirect
github.com/mitchellh/go-wordwrap v1.0.1 // indirect
github.com/ogen-go/ogen v0.19.0
github.com/sergi/go-diff v1.1.0 // indirect
github.com/zclconf/go-cty v1.10.0 // indirect
go.opentelemetry.io/otel v1.4.1
go.opentelemetry.io/otel/metric v0.27.0
go.opentelemetry.io/otel/trace v1.4.1
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.7.0 // indirect
golang.org/x/sys v0.0.0-20220222200937-f2425489ef4c // indirect
)

1014
go.sum

File diff suppressed because it is too large Load Diff

132
main.go
View File

@ -1,146 +1,76 @@
package main
import (
"strconv"
"time"
"t/ent"
"net/http"
"math/rand"
"context"
"log"
"os"
"database/sql"
entsql "entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect"
_ "github.com/jackc/pgx/v4/stdlib"
_ "github.com/lib/pq"
"net/http"
"t/ent"
"t/ent/ogent"
"entgo.io/ent/dialect/sql/schema"
"github.com/kyokomi/lottery"
"entgo.io/ent/dialect"
_ "github.com/mattn/go-sqlite3"
"time"
)
type User struct {
user string `json:"user"`
username string `json:"username"`
created_at time.Time `json:"created_at"`
}
func Open(databaseUrl string) *ent.Client {
db, err := sql.Open("pgx", databaseUrl)
if err != nil {
log.Fatal(err)
}
drv := entsql.OpenDB(dialect.Postgres, db)
return ent.NewClient(ent.Driver(drv))
}
func Random(i int) (l int){
rand.Seed(time.Now().UnixNano())
l = rand.Intn(i)
for l == 0 {
l = rand.Intn(i)
}
return
}
func Kira(i int) (l bool){
lot := lottery.New(rand.New(rand.NewSource(time.Now().UnixNano())))
if lot.Lot(i) {
l = true
} else {
l = false
}
return
}
type handler struct {
*ogent.OgentHandler
client *ent.Client
}
func (h handler) DrawStart(ctx context.Context, params ogent.DrawStartParams) (ogent.DrawStartNoContent, error) {
return ogent.DrawStartNoContent{}, h.client.Users.UpdateOneID(params.ID).Exec(ctx)
func (h handler) DrawStart(ctx context.Context, params ogent.DrawStartParams) error {
error := h.client.Card.UpdateOneID(params.ID).Exec(ctx)
return (error)
}
func (h handler) DrawDone(ctx context.Context, params ogent.DrawDoneParams) (ogent.DrawDoneNoContent, error) {
body := h.client.Users.GetX(ctx, params.ID)
total := body.Day
total_n := total + 1
//func (h handler) DrawDone(ctx context.Context, params ogent.DrawDoneParams) (ogent.DrawDoneNoContent, error) {
func (h handler) DrawDone(ctx context.Context, params ogent.DrawDoneParams) error {
body := h.client.Card.GetX(ctx, params.ID)
u_body := h.client.User.GetX(ctx, params.ID)
jst, err := time.LoadLocation("Asia/Tokyo")
if err != nil {
panic(err)
}
t := time.Now().In(jst)
tt := t.Format("20060102")
f := body.UpdatedAt.Add(time.Hour * 24 * 1).In(jst)
f := body.CreatedAt.Add(time.Hour * 24 * 1).In(jst)
ff := f.Format("20060102")
fff := body.Next
fff := u_body.Next
if tt < fff {
return ogent.DrawDoneNoContent{}, h.client.Users.UpdateOneID(params.ID).SetNext(ff).SetLimit(true).Exec(ctx)
error := h.client.User.UpdateOneID(params.ID).SetNext(ff).Exec(ctx)
return (error)
}
bb := h.client.Users.GetX(ctx, body.Battle)
ba := bb.Attack
aa := body.Attack
attack_p := aa - ba
win_n := body.Win + 1
pat := float64(win_n) / float64(total_n) * 100
var at int
if attack_p > 0 {
at = Random(55)
} else {
at = Random(45)
}
if at > 25 {
b := Random(4)
if b == 1 {
b := Random(10)
com := "attack+" + strconv.Itoa(b)
a := body.Attack + b
return ogent.DrawDoneNoContent{}, h.client.Users.UpdateOneID(params.ID).SetAttack(a).SetUpdatedAt(t).SetNext(ff).SetDay(total_n).SetWin(win_n).SetPercentage(pat).SetLimit(false).SetComment(com).Exec(ctx)
} else if b == 2 {
b := Random(10)
com := "defense+" + strconv.Itoa(b)
a := body.Defense + b
return ogent.DrawDoneNoContent{}, h.client.Users.UpdateOneID(params.ID).SetDefense(a).SetUpdatedAt(t).SetNext(ff).SetDay(total_n).SetWin(win_n).SetPercentage(pat).SetLimit(false).SetComment(com).Exec(ctx)
} else if b == 3 {
b := Random(10)
com := "hp+" + strconv.Itoa(b)
a := body.Hp + b
return ogent.DrawDoneNoContent{}, h.client.Users.UpdateOneID(params.ID).SetHp(a).SetUpdatedAt(t).SetNext(ff).SetDay(total_n).SetWin(win_n).SetPercentage(pat).SetComment(com).SetLimit(false).Exec(ctx)
} else {
b := Random(10)
com := "critical+" + strconv.Itoa(b)
a := body.Critical + b
return ogent.DrawDoneNoContent{}, h.client.Users.UpdateOneID(params.ID).SetCritical(a).SetUpdatedAt(t).SetNext(ff).SetDay(total_n).SetWin(win_n).SetPercentage(pat).SetComment(com).SetLimit(false).SetWin(win_n).Exec(ctx)
}
} else {
com := "loss"
return ogent.DrawDoneNoContent{}, h.client.Users.UpdateOneID(params.ID).SetNext(ff).SetDay(total_n).SetComment(com).SetLimit(false).Exec(ctx)
}
error := h.client.User.UpdateOneID(params.ID).SetUpdatedAt(t).Exec(ctx)
return (error)
}
func main() {
url := os.Getenv("DATABASE_URL") + "?sslmode=require"
client, err := ent.Open("postgres", url)
//client, err := Open(url)
if err := client.Schema.Create(context.Background(), schema.WithAtlas(true)); err != nil {
// Create ent client.
client, err := ent.Open(dialect.SQLite, "file:/data/ent.sqlite?_fk=1")
//client, err := ent.Open(dialect.SQLite, "file:data?mode=memory&cache=shared&_fk=1")
if err != nil {
log.Fatal(err)
}
port := os.Getenv("PORT")
if port == "" {
port = "8080"
// Run the migrations.
if err := client.Schema.Create(context.Background()); err != nil {
log.Fatal(err)
}
// Create the handler.
h := handler{
OgentHandler: ogent.NewOgentHandler(client),
client: client,
}
srv,err := ogent.NewServer(h)
// Start listening.
srv, err := ogent.NewServer(h)
//srv,err := ogent.NewServer(ogent.NewOgentHandler(client))
if err != nil {
log.Fatal(err)
}
if err := http.ListenAndServe(":" + port, srv); err != nil {
if err := http.ListenAndServe(":8080", srv); err != nil {
log.Fatal(err)
}
}

View File

@ -1,34 +1,34 @@
heroku open-api ent example
- go-module-name : t
- onconflict
### build
```sh
$ curl -X POST -H "Content-Type: application/json" -d '{"user":"syui"}' api.syui.cf/users
...ok
$ vim ent/entc.go
$ vim ent/schema/users.go
$ go generate ./...
$ go build
$ ./card
$ go generate ./...
$ go run -mod=mod main.go
$ curl -X POST -H "Content-Type: application/json" -d '{"username":"syui"}' localhost:8080/users
$ curl -X POST -H "Content-Type: application/json" -d '{"owner":1}' localhost:8080/cards
$ curl localhost:8080/users
$ curl localhost:8080/cards
$ curl localhost:8080/users/1
$ curl localhost:8080/users/1/card
```
### use
```sh
$ curl -X POST -H "Content-Type: application/json" -d '{"username":"syui"}' https://api.syui.ai/users
# onconflict
$ !!
...err
$ heroku logs
$ curl -sL https://api.syui.ai/users/1
```
```sh
# delete
$ curl -X DELETE https://api.syui.cf/users/1
# card draw
$ curl -X PUT api.syui.cf/users/1/d
$ curl api.syui.cf/users/1
# patch
$ curl -X PATCH -H "Content-Type: application/json" -d '{"battle":2}' api.syui.cf/users/1
$ curl -X PATCH -H "Content-Type: application/json" -d '{"limit":false}' api.syui.cf/users/1
$ d=`date "+%Y%m%d"`
$ curl -X PATCH -H "Content-Type: application/json" -d "{\"next\":\"$d\"}" api.syui.cf/users/1
```
### ref
```sh
$ vim ./ent/ogent/ogent.go
@ -59,20 +59,13 @@ func (h *OgentHandler) UpdateUsers(ctx context.Context, req UpdateUsersReq, para
//}
```
ref :
- https://github.com/ent/ent/blob/master/dialect/sql/schema/postgres_test.go
- https://github.com/go-kratos/beer-shop/tree/main/app/catalog/service/internal/data/ent
### link
- https://entgo.io/ja/blog/2022/02/15/generate-rest-crud-with-ent-and-ogen/
- https://github.com/ariga/ogent/blob/main/example/todo/ent/entc.go
```sh
$ vim ent/entc.go
$ vim ent/schema/users.go
$ go generate ./...
$ go build
$ ./t
```
- https://github.com/ent/ent/blob/master/dialect/sql/schema/postgres_test.go
- https://github.com/go-kratos/beer-shop/tree/main/app/catalog/service/internal/data/ent