1
0

Compare commits

..

1 Commits

Author SHA1 Message Date
5da7a10ac2 name change 2024-02-21 16:06:08 +09:00
219 changed files with 77056 additions and 7488 deletions

13
.gitignore vendored
View File

@@ -1,19 +1,10 @@
t t
api
.env .env
*.json *.json
*.sqlite *.sqlite
#*.zsh
tmp/card_limit.zsh tmp/card_limit.zsh
tmp/card_day.zsh tmp/card_day.zsh
tmp/card_delete.zsh tmp/card_delete.zsh
memo.md memo.md
api
**.DS_Store
node_modules
target
pnpm-lock.yaml
**Cargo.lock
*/target/
*/**/*.rs.bk
*/Cargo.lock

3
.gitmodules vendored
View File

@@ -1,3 +0,0 @@
[submodule "scpt"]
path = scpt
url = git@git.syui.ai:ai/api_scpt

View File

@@ -1,8 +0,0 @@
[package]
name = "api"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

1
Procfile Normal file
View File

@@ -0,0 +1 @@
web: bin/api

23
build.zsh Executable file
View File

@@ -0,0 +1,23 @@
#!/bin/zsh
d=${0:a:h}
cd $d
su=5000
go generate ./...
cp -rf $d/ent/openapi.json $d/tmp/
case $OSTYPE in
darwin*)
sed -i '' "s/255/$su/g" $d/ent/ogent/oas_parameters_gen.go
sed -i '' "s/255/$su/g" $d/ent/openapi.json
;;
linux*)
sed -i "s/255/$su/g" $d/ent/ogent/oas_parameters_gen.go
sed -i "s/255/$su/g" $d/ent/openapi.json
;;
esac
cp -rf $d/tmp/ogent ent/
PASS=`cat token.json|jq -r .password` TOKEN=`cat token.json|jq -r .token` go build
#PASS=`cat token.json|jq -r .password` TOKEN=`cat token.json|jq -r .token` go run -mod=mod main.go

View File

@@ -1,11 +0,0 @@
services:
api:
ports:
- 8080:8080
build:
context: .
restart: always
env_file:
- .env
volumes:
- ./app/data:/app/data

View File

@@ -1,32 +0,0 @@
## openapi
```sh
cargo init api
cd api
pnpm init
pnpm add -D @openapitools/openapi-generator-cli @stoplight/prism-cli
---
curl -sL http://127.0.0.1:4010
```
```sh
# mac
brew install java
sudo ln -sfn $(brew --prefix)/opt/openjdk/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk
```
## openapi-gen
```sh
# test
pnpm prism
pnpm test-gen
cd test
cargo build
# dev
pnpm gen
cd openapi
cargo build
```

244
ent/card.go Normal file
View File

@@ -0,0 +1,244 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"api/ent/card"
"api/ent/user"
"fmt"
"strings"
"time"
"entgo.io/ent"
"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"`
// Password holds the value of the "password" field.
Password string `json:"-"`
// Card holds the value of the "card" field.
Card int `json:"card,omitempty"`
// Skill holds the value of the "skill" field.
Skill string `json:"skill,omitempty"`
// Status holds the value of the "status" field.
Status string `json:"status,omitempty"`
// Token holds the value of the "token" field.
Token string `json:"-"`
// 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"`
// Count holds the value of the "count" field.
Count int `json:"count,omitempty"`
// Author holds the value of the "author" field.
Author string `json:"author,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
selectValues sql.SelectValues
}
// 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, card.FieldCount:
values[i] = new(sql.NullInt64)
case card.FieldPassword, card.FieldSkill, card.FieldStatus, card.FieldToken, card.FieldURL, card.FieldAuthor:
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:
values[i] = new(sql.UnknownType)
}
}
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.FieldPassword:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field password", values[i])
} else if value.Valid {
c.Password = value.String
}
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.FieldSkill:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field skill", values[i])
} else if value.Valid {
c.Skill = value.String
}
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.FieldToken:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field token", values[i])
} else if value.Valid {
c.Token = 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.FieldCount:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field count", values[i])
} else if value.Valid {
c.Count = int(value.Int64)
}
case card.FieldAuthor:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field author", values[i])
} else if value.Valid {
c.Author = 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)
}
default:
c.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Card.
// This includes values selected through modifiers, order, etc.
func (c *Card) Value(name string) (ent.Value, error) {
return c.selectValues.Get(name)
}
// 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("password=<sensitive>")
builder.WriteString(", ")
builder.WriteString("card=")
builder.WriteString(fmt.Sprintf("%v", c.Card))
builder.WriteString(", ")
builder.WriteString("skill=")
builder.WriteString(c.Skill)
builder.WriteString(", ")
builder.WriteString("status=")
builder.WriteString(c.Status)
builder.WriteString(", ")
builder.WriteString("token=<sensitive>")
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("count=")
builder.WriteString(fmt.Sprintf("%v", c.Count))
builder.WriteString(", ")
builder.WriteString("author=")
builder.WriteString(c.Author)
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

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

@@ -0,0 +1,175 @@
// Code generated by ent, DO NOT EDIT.
package card
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
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"
// FieldPassword holds the string denoting the password field in the database.
FieldPassword = "password"
// FieldCard holds the string denoting the card field in the database.
FieldCard = "card"
// FieldSkill holds the string denoting the skill field in the database.
FieldSkill = "skill"
// FieldStatus holds the string denoting the status field in the database.
FieldStatus = "status"
// FieldToken holds the string denoting the token field in the database.
FieldToken = "token"
// 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"
// FieldCount holds the string denoting the count field in the database.
FieldCount = "count"
// FieldAuthor holds the string denoting the author field in the database.
FieldAuthor = "author"
// 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,
FieldPassword,
FieldCard,
FieldSkill,
FieldStatus,
FieldToken,
FieldCp,
FieldURL,
FieldCount,
FieldAuthor,
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 (
// PasswordValidator is a validator for the "password" field. It is called by the builders before save.
PasswordValidator func(string) error
// DefaultCard holds the default value on creation for the "card" field.
DefaultCard func() int
// DefaultSkill holds the default value on creation for the "skill" field.
DefaultSkill func() string
// 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
// DefaultAuthor holds the default value on creation for the "author" field.
DefaultAuthor string
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
)
// OrderOption defines the ordering options for the Card queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByPassword orders the results by the password field.
func ByPassword(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPassword, opts...).ToFunc()
}
// ByCard orders the results by the card field.
func ByCard(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCard, opts...).ToFunc()
}
// BySkill orders the results by the skill field.
func BySkill(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSkill, opts...).ToFunc()
}
// ByStatus orders the results by the status field.
func ByStatus(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldStatus, opts...).ToFunc()
}
// ByToken orders the results by the token field.
func ByToken(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldToken, opts...).ToFunc()
}
// ByCp orders the results by the cp field.
func ByCp(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCp, opts...).ToFunc()
}
// ByURL orders the results by the url field.
func ByURL(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldURL, opts...).ToFunc()
}
// ByCount orders the results by the count field.
func ByCount(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCount, opts...).ToFunc()
}
// ByAuthor orders the results by the author field.
func ByAuthor(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldAuthor, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByOwnerField orders the results by owner field.
func ByOwnerField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newOwnerStep(), sql.OrderByField(field, opts...))
}
}
func newOwnerStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(OwnerInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
)
}

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

@@ -0,0 +1,801 @@
// Code generated by ent, DO NOT EDIT.
package card
import (
"api/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))
}
// Password applies equality check predicate on the "password" field. It's identical to PasswordEQ.
func Password(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldPassword, v))
}
// 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))
}
// Skill applies equality check predicate on the "skill" field. It's identical to SkillEQ.
func Skill(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldSkill, 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))
}
// Token applies equality check predicate on the "token" field. It's identical to TokenEQ.
func Token(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldToken, 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))
}
// Count applies equality check predicate on the "count" field. It's identical to CountEQ.
func Count(v int) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldCount, v))
}
// Author applies equality check predicate on the "author" field. It's identical to AuthorEQ.
func Author(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldAuthor, 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))
}
// PasswordEQ applies the EQ predicate on the "password" field.
func PasswordEQ(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldPassword, v))
}
// PasswordNEQ applies the NEQ predicate on the "password" field.
func PasswordNEQ(v string) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldPassword, v))
}
// PasswordIn applies the In predicate on the "password" field.
func PasswordIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldIn(FieldPassword, vs...))
}
// PasswordNotIn applies the NotIn predicate on the "password" field.
func PasswordNotIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldPassword, vs...))
}
// PasswordGT applies the GT predicate on the "password" field.
func PasswordGT(v string) predicate.Card {
return predicate.Card(sql.FieldGT(FieldPassword, v))
}
// PasswordGTE applies the GTE predicate on the "password" field.
func PasswordGTE(v string) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldPassword, v))
}
// PasswordLT applies the LT predicate on the "password" field.
func PasswordLT(v string) predicate.Card {
return predicate.Card(sql.FieldLT(FieldPassword, v))
}
// PasswordLTE applies the LTE predicate on the "password" field.
func PasswordLTE(v string) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldPassword, v))
}
// PasswordContains applies the Contains predicate on the "password" field.
func PasswordContains(v string) predicate.Card {
return predicate.Card(sql.FieldContains(FieldPassword, v))
}
// PasswordHasPrefix applies the HasPrefix predicate on the "password" field.
func PasswordHasPrefix(v string) predicate.Card {
return predicate.Card(sql.FieldHasPrefix(FieldPassword, v))
}
// PasswordHasSuffix applies the HasSuffix predicate on the "password" field.
func PasswordHasSuffix(v string) predicate.Card {
return predicate.Card(sql.FieldHasSuffix(FieldPassword, v))
}
// PasswordEqualFold applies the EqualFold predicate on the "password" field.
func PasswordEqualFold(v string) predicate.Card {
return predicate.Card(sql.FieldEqualFold(FieldPassword, v))
}
// PasswordContainsFold applies the ContainsFold predicate on the "password" field.
func PasswordContainsFold(v string) predicate.Card {
return predicate.Card(sql.FieldContainsFold(FieldPassword, 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))
}
// SkillEQ applies the EQ predicate on the "skill" field.
func SkillEQ(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldSkill, v))
}
// SkillNEQ applies the NEQ predicate on the "skill" field.
func SkillNEQ(v string) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldSkill, v))
}
// SkillIn applies the In predicate on the "skill" field.
func SkillIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldIn(FieldSkill, vs...))
}
// SkillNotIn applies the NotIn predicate on the "skill" field.
func SkillNotIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldSkill, vs...))
}
// SkillGT applies the GT predicate on the "skill" field.
func SkillGT(v string) predicate.Card {
return predicate.Card(sql.FieldGT(FieldSkill, v))
}
// SkillGTE applies the GTE predicate on the "skill" field.
func SkillGTE(v string) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldSkill, v))
}
// SkillLT applies the LT predicate on the "skill" field.
func SkillLT(v string) predicate.Card {
return predicate.Card(sql.FieldLT(FieldSkill, v))
}
// SkillLTE applies the LTE predicate on the "skill" field.
func SkillLTE(v string) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldSkill, v))
}
// SkillContains applies the Contains predicate on the "skill" field.
func SkillContains(v string) predicate.Card {
return predicate.Card(sql.FieldContains(FieldSkill, v))
}
// SkillHasPrefix applies the HasPrefix predicate on the "skill" field.
func SkillHasPrefix(v string) predicate.Card {
return predicate.Card(sql.FieldHasPrefix(FieldSkill, v))
}
// SkillHasSuffix applies the HasSuffix predicate on the "skill" field.
func SkillHasSuffix(v string) predicate.Card {
return predicate.Card(sql.FieldHasSuffix(FieldSkill, v))
}
// SkillIsNil applies the IsNil predicate on the "skill" field.
func SkillIsNil() predicate.Card {
return predicate.Card(sql.FieldIsNull(FieldSkill))
}
// SkillNotNil applies the NotNil predicate on the "skill" field.
func SkillNotNil() predicate.Card {
return predicate.Card(sql.FieldNotNull(FieldSkill))
}
// SkillEqualFold applies the EqualFold predicate on the "skill" field.
func SkillEqualFold(v string) predicate.Card {
return predicate.Card(sql.FieldEqualFold(FieldSkill, v))
}
// SkillContainsFold applies the ContainsFold predicate on the "skill" field.
func SkillContainsFold(v string) predicate.Card {
return predicate.Card(sql.FieldContainsFold(FieldSkill, v))
}
// 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))
}
// TokenEQ applies the EQ predicate on the "token" field.
func TokenEQ(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldToken, v))
}
// TokenNEQ applies the NEQ predicate on the "token" field.
func TokenNEQ(v string) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldToken, v))
}
// TokenIn applies the In predicate on the "token" field.
func TokenIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldIn(FieldToken, vs...))
}
// TokenNotIn applies the NotIn predicate on the "token" field.
func TokenNotIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldToken, vs...))
}
// TokenGT applies the GT predicate on the "token" field.
func TokenGT(v string) predicate.Card {
return predicate.Card(sql.FieldGT(FieldToken, v))
}
// TokenGTE applies the GTE predicate on the "token" field.
func TokenGTE(v string) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldToken, v))
}
// TokenLT applies the LT predicate on the "token" field.
func TokenLT(v string) predicate.Card {
return predicate.Card(sql.FieldLT(FieldToken, v))
}
// TokenLTE applies the LTE predicate on the "token" field.
func TokenLTE(v string) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldToken, v))
}
// TokenContains applies the Contains predicate on the "token" field.
func TokenContains(v string) predicate.Card {
return predicate.Card(sql.FieldContains(FieldToken, v))
}
// TokenHasPrefix applies the HasPrefix predicate on the "token" field.
func TokenHasPrefix(v string) predicate.Card {
return predicate.Card(sql.FieldHasPrefix(FieldToken, v))
}
// TokenHasSuffix applies the HasSuffix predicate on the "token" field.
func TokenHasSuffix(v string) predicate.Card {
return predicate.Card(sql.FieldHasSuffix(FieldToken, v))
}
// TokenIsNil applies the IsNil predicate on the "token" field.
func TokenIsNil() predicate.Card {
return predicate.Card(sql.FieldIsNull(FieldToken))
}
// TokenNotNil applies the NotNil predicate on the "token" field.
func TokenNotNil() predicate.Card {
return predicate.Card(sql.FieldNotNull(FieldToken))
}
// TokenEqualFold applies the EqualFold predicate on the "token" field.
func TokenEqualFold(v string) predicate.Card {
return predicate.Card(sql.FieldEqualFold(FieldToken, v))
}
// TokenContainsFold applies the ContainsFold predicate on the "token" field.
func TokenContainsFold(v string) predicate.Card {
return predicate.Card(sql.FieldContainsFold(FieldToken, 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))
}
// CountEQ applies the EQ predicate on the "count" field.
func CountEQ(v int) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldCount, v))
}
// CountNEQ applies the NEQ predicate on the "count" field.
func CountNEQ(v int) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldCount, v))
}
// CountIn applies the In predicate on the "count" field.
func CountIn(vs ...int) predicate.Card {
return predicate.Card(sql.FieldIn(FieldCount, vs...))
}
// CountNotIn applies the NotIn predicate on the "count" field.
func CountNotIn(vs ...int) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldCount, vs...))
}
// CountGT applies the GT predicate on the "count" field.
func CountGT(v int) predicate.Card {
return predicate.Card(sql.FieldGT(FieldCount, v))
}
// CountGTE applies the GTE predicate on the "count" field.
func CountGTE(v int) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldCount, v))
}
// CountLT applies the LT predicate on the "count" field.
func CountLT(v int) predicate.Card {
return predicate.Card(sql.FieldLT(FieldCount, v))
}
// CountLTE applies the LTE predicate on the "count" field.
func CountLTE(v int) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldCount, v))
}
// CountIsNil applies the IsNil predicate on the "count" field.
func CountIsNil() predicate.Card {
return predicate.Card(sql.FieldIsNull(FieldCount))
}
// CountNotNil applies the NotNil predicate on the "count" field.
func CountNotNil() predicate.Card {
return predicate.Card(sql.FieldNotNull(FieldCount))
}
// AuthorEQ applies the EQ predicate on the "author" field.
func AuthorEQ(v string) predicate.Card {
return predicate.Card(sql.FieldEQ(FieldAuthor, v))
}
// AuthorNEQ applies the NEQ predicate on the "author" field.
func AuthorNEQ(v string) predicate.Card {
return predicate.Card(sql.FieldNEQ(FieldAuthor, v))
}
// AuthorIn applies the In predicate on the "author" field.
func AuthorIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldIn(FieldAuthor, vs...))
}
// AuthorNotIn applies the NotIn predicate on the "author" field.
func AuthorNotIn(vs ...string) predicate.Card {
return predicate.Card(sql.FieldNotIn(FieldAuthor, vs...))
}
// AuthorGT applies the GT predicate on the "author" field.
func AuthorGT(v string) predicate.Card {
return predicate.Card(sql.FieldGT(FieldAuthor, v))
}
// AuthorGTE applies the GTE predicate on the "author" field.
func AuthorGTE(v string) predicate.Card {
return predicate.Card(sql.FieldGTE(FieldAuthor, v))
}
// AuthorLT applies the LT predicate on the "author" field.
func AuthorLT(v string) predicate.Card {
return predicate.Card(sql.FieldLT(FieldAuthor, v))
}
// AuthorLTE applies the LTE predicate on the "author" field.
func AuthorLTE(v string) predicate.Card {
return predicate.Card(sql.FieldLTE(FieldAuthor, v))
}
// AuthorContains applies the Contains predicate on the "author" field.
func AuthorContains(v string) predicate.Card {
return predicate.Card(sql.FieldContains(FieldAuthor, v))
}
// AuthorHasPrefix applies the HasPrefix predicate on the "author" field.
func AuthorHasPrefix(v string) predicate.Card {
return predicate.Card(sql.FieldHasPrefix(FieldAuthor, v))
}
// AuthorHasSuffix applies the HasSuffix predicate on the "author" field.
func AuthorHasSuffix(v string) predicate.Card {
return predicate.Card(sql.FieldHasSuffix(FieldAuthor, v))
}
// AuthorIsNil applies the IsNil predicate on the "author" field.
func AuthorIsNil() predicate.Card {
return predicate.Card(sql.FieldIsNull(FieldAuthor))
}
// AuthorNotNil applies the NotNil predicate on the "author" field.
func AuthorNotNil() predicate.Card {
return predicate.Card(sql.FieldNotNull(FieldAuthor))
}
// AuthorEqualFold applies the EqualFold predicate on the "author" field.
func AuthorEqualFold(v string) predicate.Card {
return predicate.Card(sql.FieldEqualFold(FieldAuthor, v))
}
// AuthorContainsFold applies the ContainsFold predicate on the "author" field.
func AuthorContainsFold(v string) predicate.Card {
return predicate.Card(sql.FieldContainsFold(FieldAuthor, 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 := newOwnerStep()
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())
})
}

413
ent/card_create.go Normal file
View File

@@ -0,0 +1,413 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"api/ent/card"
"api/ent/user"
"context"
"errors"
"fmt"
"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
}
// SetPassword sets the "password" field.
func (cc *CardCreate) SetPassword(s string) *CardCreate {
cc.mutation.SetPassword(s)
return cc
}
// 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
}
// SetSkill sets the "skill" field.
func (cc *CardCreate) SetSkill(s string) *CardCreate {
cc.mutation.SetSkill(s)
return cc
}
// SetNillableSkill sets the "skill" field if the given value is not nil.
func (cc *CardCreate) SetNillableSkill(s *string) *CardCreate {
if s != nil {
cc.SetSkill(*s)
}
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
}
// SetToken sets the "token" field.
func (cc *CardCreate) SetToken(s string) *CardCreate {
cc.mutation.SetToken(s)
return cc
}
// SetNillableToken sets the "token" field if the given value is not nil.
func (cc *CardCreate) SetNillableToken(s *string) *CardCreate {
if s != nil {
cc.SetToken(*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
}
// SetCount sets the "count" field.
func (cc *CardCreate) SetCount(i int) *CardCreate {
cc.mutation.SetCount(i)
return cc
}
// SetNillableCount sets the "count" field if the given value is not nil.
func (cc *CardCreate) SetNillableCount(i *int) *CardCreate {
if i != nil {
cc.SetCount(*i)
}
return cc
}
// SetAuthor sets the "author" field.
func (cc *CardCreate) SetAuthor(s string) *CardCreate {
cc.mutation.SetAuthor(s)
return cc
}
// SetNillableAuthor sets the "author" field if the given value is not nil.
func (cc *CardCreate) SetNillableAuthor(s *string) *CardCreate {
if s != nil {
cc.SetAuthor(*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.Skill(); !ok {
v := card.DefaultSkill()
cc.mutation.SetSkill(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.Author(); !ok {
v := card.DefaultAuthor
cc.mutation.SetAuthor(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.Password(); !ok {
return &ValidationError{Name: "password", err: errors.New(`ent: missing required field "Card.password"`)}
}
if v, ok := cc.mutation.Password(); ok {
if err := card.PasswordValidator(v); err != nil {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "Card.password": %w`, err)}
}
}
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.Password(); ok {
_spec.SetField(card.FieldPassword, field.TypeString, value)
_node.Password = value
}
if value, ok := cc.mutation.Card(); ok {
_spec.SetField(card.FieldCard, field.TypeInt, value)
_node.Card = value
}
if value, ok := cc.mutation.Skill(); ok {
_spec.SetField(card.FieldSkill, field.TypeString, value)
_node.Skill = value
}
if value, ok := cc.mutation.Status(); ok {
_spec.SetField(card.FieldStatus, field.TypeString, value)
_node.Status = value
}
if value, ok := cc.mutation.Token(); ok {
_spec.SetField(card.FieldToken, field.TypeString, value)
_node.Token = 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.Count(); ok {
_spec.SetField(card.FieldCount, field.TypeInt, value)
_node.Count = value
}
if value, ok := cc.mutation.Author(); ok {
_spec.SetField(card.FieldAuthor, field.TypeString, value)
_node.Author = 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.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
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
var err error
nodes[i], specs[i] = builder.createSpec()
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 (
"api/ent/card"
"api/ent/predicate"
"context"
"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 (
"api/ent/card"
"api/ent/predicate"
"api/ent/user"
"context"
"fmt"
"math"
"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 []card.OrderOption
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 ...card.OrderOption) *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([]card.OrderOption{}, 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 {
// Password string `json:"password,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Card.Query().
// GroupBy(card.FieldPassword).
// 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 {
// Password string `json:"password,omitempty"`
// }
//
// client.Card.Query().
// Select(card.FieldPassword).
// 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)
}

772
ent/card_update.go Normal file
View File

@@ -0,0 +1,772 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"api/ent/card"
"api/ent/predicate"
"api/ent/user"
"context"
"errors"
"fmt"
"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
}
// SetCard sets the "card" field.
func (cu *CardUpdate) SetCard(i int) *CardUpdate {
cu.mutation.ResetCard()
cu.mutation.SetCard(i)
return cu
}
// SetNillableCard sets the "card" field if the given value is not nil.
func (cu *CardUpdate) SetNillableCard(i *int) *CardUpdate {
if i != nil {
cu.SetCard(*i)
}
return cu
}
// AddCard adds i to the "card" field.
func (cu *CardUpdate) AddCard(i int) *CardUpdate {
cu.mutation.AddCard(i)
return cu
}
// ClearCard clears the value of the "card" field.
func (cu *CardUpdate) ClearCard() *CardUpdate {
cu.mutation.ClearCard()
return cu
}
// SetSkill sets the "skill" field.
func (cu *CardUpdate) SetSkill(s string) *CardUpdate {
cu.mutation.SetSkill(s)
return cu
}
// SetNillableSkill sets the "skill" field if the given value is not nil.
func (cu *CardUpdate) SetNillableSkill(s *string) *CardUpdate {
if s != nil {
cu.SetSkill(*s)
}
return cu
}
// ClearSkill clears the value of the "skill" field.
func (cu *CardUpdate) ClearSkill() *CardUpdate {
cu.mutation.ClearSkill()
return cu
}
// SetStatus sets the "status" field.
func (cu *CardUpdate) SetStatus(s string) *CardUpdate {
cu.mutation.SetStatus(s)
return cu
}
// SetNillableStatus sets the "status" field if the given value is not nil.
func (cu *CardUpdate) SetNillableStatus(s *string) *CardUpdate {
if s != nil {
cu.SetStatus(*s)
}
return cu
}
// ClearStatus clears the value of the "status" field.
func (cu *CardUpdate) ClearStatus() *CardUpdate {
cu.mutation.ClearStatus()
return cu
}
// SetToken sets the "token" field.
func (cu *CardUpdate) SetToken(s string) *CardUpdate {
cu.mutation.SetToken(s)
return cu
}
// SetNillableToken sets the "token" field if the given value is not nil.
func (cu *CardUpdate) SetNillableToken(s *string) *CardUpdate {
if s != nil {
cu.SetToken(*s)
}
return cu
}
// ClearToken clears the value of the "token" field.
func (cu *CardUpdate) ClearToken() *CardUpdate {
cu.mutation.ClearToken()
return cu
}
// SetCp sets the "cp" field.
func (cu *CardUpdate) SetCp(i int) *CardUpdate {
cu.mutation.ResetCp()
cu.mutation.SetCp(i)
return cu
}
// SetNillableCp sets the "cp" field if the given value is not nil.
func (cu *CardUpdate) SetNillableCp(i *int) *CardUpdate {
if i != nil {
cu.SetCp(*i)
}
return cu
}
// AddCp adds i to the "cp" field.
func (cu *CardUpdate) AddCp(i int) *CardUpdate {
cu.mutation.AddCp(i)
return cu
}
// ClearCp clears the value of the "cp" field.
func (cu *CardUpdate) ClearCp() *CardUpdate {
cu.mutation.ClearCp()
return cu
}
// SetURL sets the "url" field.
func (cu *CardUpdate) SetURL(s string) *CardUpdate {
cu.mutation.SetURL(s)
return cu
}
// SetNillableURL sets the "url" field if the given value is not nil.
func (cu *CardUpdate) SetNillableURL(s *string) *CardUpdate {
if s != nil {
cu.SetURL(*s)
}
return cu
}
// ClearURL clears the value of the "url" field.
func (cu *CardUpdate) ClearURL() *CardUpdate {
cu.mutation.ClearURL()
return cu
}
// SetCount sets the "count" field.
func (cu *CardUpdate) SetCount(i int) *CardUpdate {
cu.mutation.ResetCount()
cu.mutation.SetCount(i)
return cu
}
// SetNillableCount sets the "count" field if the given value is not nil.
func (cu *CardUpdate) SetNillableCount(i *int) *CardUpdate {
if i != nil {
cu.SetCount(*i)
}
return cu
}
// AddCount adds i to the "count" field.
func (cu *CardUpdate) AddCount(i int) *CardUpdate {
cu.mutation.AddCount(i)
return cu
}
// ClearCount clears the value of the "count" field.
func (cu *CardUpdate) ClearCount() *CardUpdate {
cu.mutation.ClearCount()
return cu
}
// SetAuthor sets the "author" field.
func (cu *CardUpdate) SetAuthor(s string) *CardUpdate {
cu.mutation.SetAuthor(s)
return cu
}
// SetNillableAuthor sets the "author" field if the given value is not nil.
func (cu *CardUpdate) SetNillableAuthor(s *string) *CardUpdate {
if s != nil {
cu.SetAuthor(*s)
}
return cu
}
// ClearAuthor clears the value of the "author" field.
func (cu *CardUpdate) ClearAuthor() *CardUpdate {
cu.mutation.ClearAuthor()
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 value, ok := cu.mutation.Card(); ok {
_spec.SetField(card.FieldCard, field.TypeInt, value)
}
if value, ok := cu.mutation.AddedCard(); ok {
_spec.AddField(card.FieldCard, field.TypeInt, value)
}
if cu.mutation.CardCleared() {
_spec.ClearField(card.FieldCard, field.TypeInt)
}
if value, ok := cu.mutation.Skill(); ok {
_spec.SetField(card.FieldSkill, field.TypeString, value)
}
if cu.mutation.SkillCleared() {
_spec.ClearField(card.FieldSkill, field.TypeString)
}
if value, ok := cu.mutation.Status(); ok {
_spec.SetField(card.FieldStatus, field.TypeString, value)
}
if cu.mutation.StatusCleared() {
_spec.ClearField(card.FieldStatus, field.TypeString)
}
if value, ok := cu.mutation.Token(); ok {
_spec.SetField(card.FieldToken, field.TypeString, value)
}
if cu.mutation.TokenCleared() {
_spec.ClearField(card.FieldToken, field.TypeString)
}
if value, ok := cu.mutation.Cp(); ok {
_spec.SetField(card.FieldCp, field.TypeInt, value)
}
if value, ok := cu.mutation.AddedCp(); ok {
_spec.AddField(card.FieldCp, field.TypeInt, value)
}
if cu.mutation.CpCleared() {
_spec.ClearField(card.FieldCp, field.TypeInt)
}
if value, ok := cu.mutation.URL(); ok {
_spec.SetField(card.FieldURL, field.TypeString, value)
}
if cu.mutation.URLCleared() {
_spec.ClearField(card.FieldURL, field.TypeString)
}
if value, ok := cu.mutation.Count(); ok {
_spec.SetField(card.FieldCount, field.TypeInt, value)
}
if value, ok := cu.mutation.AddedCount(); ok {
_spec.AddField(card.FieldCount, field.TypeInt, value)
}
if cu.mutation.CountCleared() {
_spec.ClearField(card.FieldCount, field.TypeInt)
}
if value, ok := cu.mutation.Author(); ok {
_spec.SetField(card.FieldAuthor, field.TypeString, value)
}
if cu.mutation.AuthorCleared() {
_spec.ClearField(card.FieldAuthor, 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.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_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.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if 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
}
// SetCard sets the "card" field.
func (cuo *CardUpdateOne) SetCard(i int) *CardUpdateOne {
cuo.mutation.ResetCard()
cuo.mutation.SetCard(i)
return cuo
}
// SetNillableCard sets the "card" field if the given value is not nil.
func (cuo *CardUpdateOne) SetNillableCard(i *int) *CardUpdateOne {
if i != nil {
cuo.SetCard(*i)
}
return cuo
}
// AddCard adds i to the "card" field.
func (cuo *CardUpdateOne) AddCard(i int) *CardUpdateOne {
cuo.mutation.AddCard(i)
return cuo
}
// ClearCard clears the value of the "card" field.
func (cuo *CardUpdateOne) ClearCard() *CardUpdateOne {
cuo.mutation.ClearCard()
return cuo
}
// SetSkill sets the "skill" field.
func (cuo *CardUpdateOne) SetSkill(s string) *CardUpdateOne {
cuo.mutation.SetSkill(s)
return cuo
}
// SetNillableSkill sets the "skill" field if the given value is not nil.
func (cuo *CardUpdateOne) SetNillableSkill(s *string) *CardUpdateOne {
if s != nil {
cuo.SetSkill(*s)
}
return cuo
}
// ClearSkill clears the value of the "skill" field.
func (cuo *CardUpdateOne) ClearSkill() *CardUpdateOne {
cuo.mutation.ClearSkill()
return cuo
}
// SetStatus sets the "status" field.
func (cuo *CardUpdateOne) SetStatus(s string) *CardUpdateOne {
cuo.mutation.SetStatus(s)
return cuo
}
// SetNillableStatus sets the "status" field if the given value is not nil.
func (cuo *CardUpdateOne) SetNillableStatus(s *string) *CardUpdateOne {
if s != nil {
cuo.SetStatus(*s)
}
return cuo
}
// ClearStatus clears the value of the "status" field.
func (cuo *CardUpdateOne) ClearStatus() *CardUpdateOne {
cuo.mutation.ClearStatus()
return cuo
}
// SetToken sets the "token" field.
func (cuo *CardUpdateOne) SetToken(s string) *CardUpdateOne {
cuo.mutation.SetToken(s)
return cuo
}
// SetNillableToken sets the "token" field if the given value is not nil.
func (cuo *CardUpdateOne) SetNillableToken(s *string) *CardUpdateOne {
if s != nil {
cuo.SetToken(*s)
}
return cuo
}
// ClearToken clears the value of the "token" field.
func (cuo *CardUpdateOne) ClearToken() *CardUpdateOne {
cuo.mutation.ClearToken()
return cuo
}
// SetCp sets the "cp" field.
func (cuo *CardUpdateOne) SetCp(i int) *CardUpdateOne {
cuo.mutation.ResetCp()
cuo.mutation.SetCp(i)
return cuo
}
// SetNillableCp sets the "cp" field if the given value is not nil.
func (cuo *CardUpdateOne) SetNillableCp(i *int) *CardUpdateOne {
if i != nil {
cuo.SetCp(*i)
}
return cuo
}
// AddCp adds i to the "cp" field.
func (cuo *CardUpdateOne) AddCp(i int) *CardUpdateOne {
cuo.mutation.AddCp(i)
return cuo
}
// ClearCp clears the value of the "cp" field.
func (cuo *CardUpdateOne) ClearCp() *CardUpdateOne {
cuo.mutation.ClearCp()
return cuo
}
// SetURL sets the "url" field.
func (cuo *CardUpdateOne) SetURL(s string) *CardUpdateOne {
cuo.mutation.SetURL(s)
return cuo
}
// SetNillableURL sets the "url" field if the given value is not nil.
func (cuo *CardUpdateOne) SetNillableURL(s *string) *CardUpdateOne {
if s != nil {
cuo.SetURL(*s)
}
return cuo
}
// ClearURL clears the value of the "url" field.
func (cuo *CardUpdateOne) ClearURL() *CardUpdateOne {
cuo.mutation.ClearURL()
return cuo
}
// SetCount sets the "count" field.
func (cuo *CardUpdateOne) SetCount(i int) *CardUpdateOne {
cuo.mutation.ResetCount()
cuo.mutation.SetCount(i)
return cuo
}
// SetNillableCount sets the "count" field if the given value is not nil.
func (cuo *CardUpdateOne) SetNillableCount(i *int) *CardUpdateOne {
if i != nil {
cuo.SetCount(*i)
}
return cuo
}
// AddCount adds i to the "count" field.
func (cuo *CardUpdateOne) AddCount(i int) *CardUpdateOne {
cuo.mutation.AddCount(i)
return cuo
}
// ClearCount clears the value of the "count" field.
func (cuo *CardUpdateOne) ClearCount() *CardUpdateOne {
cuo.mutation.ClearCount()
return cuo
}
// SetAuthor sets the "author" field.
func (cuo *CardUpdateOne) SetAuthor(s string) *CardUpdateOne {
cuo.mutation.SetAuthor(s)
return cuo
}
// SetNillableAuthor sets the "author" field if the given value is not nil.
func (cuo *CardUpdateOne) SetNillableAuthor(s *string) *CardUpdateOne {
if s != nil {
cuo.SetAuthor(*s)
}
return cuo
}
// ClearAuthor clears the value of the "author" field.
func (cuo *CardUpdateOne) ClearAuthor() *CardUpdateOne {
cuo.mutation.ClearAuthor()
return cuo
}
// 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 value, ok := cuo.mutation.Card(); ok {
_spec.SetField(card.FieldCard, field.TypeInt, value)
}
if value, ok := cuo.mutation.AddedCard(); ok {
_spec.AddField(card.FieldCard, field.TypeInt, value)
}
if cuo.mutation.CardCleared() {
_spec.ClearField(card.FieldCard, field.TypeInt)
}
if value, ok := cuo.mutation.Skill(); ok {
_spec.SetField(card.FieldSkill, field.TypeString, value)
}
if cuo.mutation.SkillCleared() {
_spec.ClearField(card.FieldSkill, field.TypeString)
}
if value, ok := cuo.mutation.Status(); ok {
_spec.SetField(card.FieldStatus, field.TypeString, value)
}
if cuo.mutation.StatusCleared() {
_spec.ClearField(card.FieldStatus, field.TypeString)
}
if value, ok := cuo.mutation.Token(); ok {
_spec.SetField(card.FieldToken, field.TypeString, value)
}
if cuo.mutation.TokenCleared() {
_spec.ClearField(card.FieldToken, field.TypeString)
}
if value, ok := cuo.mutation.Cp(); ok {
_spec.SetField(card.FieldCp, field.TypeInt, value)
}
if value, ok := cuo.mutation.AddedCp(); ok {
_spec.AddField(card.FieldCp, field.TypeInt, value)
}
if cuo.mutation.CpCleared() {
_spec.ClearField(card.FieldCp, field.TypeInt)
}
if value, ok := cuo.mutation.URL(); ok {
_spec.SetField(card.FieldURL, field.TypeString, value)
}
if cuo.mutation.URLCleared() {
_spec.ClearField(card.FieldURL, field.TypeString)
}
if value, ok := cuo.mutation.Count(); ok {
_spec.SetField(card.FieldCount, field.TypeInt, value)
}
if value, ok := cuo.mutation.AddedCount(); ok {
_spec.AddField(card.FieldCount, field.TypeInt, value)
}
if cuo.mutation.CountCleared() {
_spec.ClearField(card.FieldCount, field.TypeInt)
}
if value, ok := cuo.mutation.Author(); ok {
_spec.SetField(card.FieldAuthor, field.TypeString, value)
}
if cuo.mutation.AuthorCleared() {
_spec.ClearField(card.FieldAuthor, 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.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_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.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &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
}

782
ent/client.go Normal file
View File

@@ -0,0 +1,782 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"log"
"api/ent/migrate"
"api/ent/card"
"api/ent/group"
"api/ent/ue"
"api/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.
type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// Card is the client for interacting with the Card builders.
Card *CardClient
// Group is the client for interacting with the Group builders.
Group *GroupClient
// Ue is the client for interacting with the Ue builders.
Ue *UeClient
// 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{}, inters: &inters{}}
cfg.options(opts...)
client := &Client{config: cfg}
client.init()
return client
}
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.Card = NewCardClient(c.config)
c.Group = NewGroupClient(c.config)
c.Ue = NewUeClient(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
// the data source name, and returns a new client attached to it.
// Optional parameters can be added for configuring the client.
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
switch driverName {
case dialect.MySQL, dialect.Postgres, dialect.SQLite:
drv, err := sql.Open(driverName, dataSourceName)
if err != nil {
return nil, err
}
return NewClient(append(options, Driver(drv))...), nil
default:
return nil, fmt.Errorf("unsupported driver: %q", driverName)
}
}
// Tx returns a new transactional client. The provided context
// is used until the transaction is committed or rolled back.
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, errors.New("ent: cannot start a transaction within a transaction")
}
tx, err := newTx(ctx, c.driver)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = tx
return &Tx{
ctx: ctx,
config: cfg,
Card: NewCardClient(cfg),
Group: NewGroupClient(cfg),
Ue: NewUeClient(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, errors.New("ent: cannot start a transaction within a transaction")
}
tx, err := c.driver.(interface {
BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
}).BeginTx(ctx, opts)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = &txDriver{tx: tx, drv: c.driver}
return &Tx{
ctx: ctx,
config: cfg,
Card: NewCardClient(cfg),
Group: NewGroupClient(cfg),
Ue: NewUeClient(cfg),
User: NewUserClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Card.
// Query().
// Count(ctx)
func (c *Client) Debug() *Client {
if c.debug {
return c
}
cfg := c.config
cfg.driver = dialect.Debug(c.driver, c.log)
client := &Client{config: cfg}
client.init()
return client
}
// Close closes the database connection and prevents new queries from starting.
func (c *Client) Close() error {
return c.driver.Close()
}
// Use adds the mutation hooks to all the entity clients.
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) {
c.Card.Use(hooks...)
c.Group.Use(hooks...)
c.Ue.Use(hooks...)
c.User.Use(hooks...)
}
// Intercept adds the query interceptors to all the entity clients.
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
func (c *Client) Intercept(interceptors ...Interceptor) {
c.Card.Intercept(interceptors...)
c.Group.Intercept(interceptors...)
c.Ue.Intercept(interceptors...)
c.User.Intercept(interceptors...)
}
// Mutate implements the ent.Mutator interface.
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *CardMutation:
return c.Card.mutate(ctx, m)
case *GroupMutation:
return c.Group.mutate(ctx, m)
case *UeMutation:
return c.Ue.mutate(ctx, m)
case *UserMutation:
return c.User.mutate(ctx, m)
default:
return nil, fmt.Errorf("ent: unknown mutation type %T", m)
}
}
// 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 *CardClient) GetX(ctx context.Context, id int) *Card {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// 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())
}
}
// UeClient is a client for the Ue schema.
type UeClient struct {
config
}
// NewUeClient returns a client for the Ue from the given config.
func NewUeClient(c config) *UeClient {
return &UeClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `ue.Hooks(f(g(h())))`.
func (c *UeClient) Use(hooks ...Hook) {
c.hooks.Ue = append(c.hooks.Ue, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `ue.Intercept(f(g(h())))`.
func (c *UeClient) Intercept(interceptors ...Interceptor) {
c.inters.Ue = append(c.inters.Ue, interceptors...)
}
// Create returns a builder for creating a Ue entity.
func (c *UeClient) Create() *UeCreate {
mutation := newUeMutation(c.config, OpCreate)
return &UeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Ue entities.
func (c *UeClient) CreateBulk(builders ...*UeCreate) *UeCreateBulk {
return &UeCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Ue.
func (c *UeClient) Update() *UeUpdate {
mutation := newUeMutation(c.config, OpUpdate)
return &UeUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *UeClient) UpdateOne(u *Ue) *UeUpdateOne {
mutation := newUeMutation(c.config, OpUpdateOne, withUe(u))
return &UeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *UeClient) UpdateOneID(id int) *UeUpdateOne {
mutation := newUeMutation(c.config, OpUpdateOne, withUeID(id))
return &UeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Ue.
func (c *UeClient) Delete() *UeDelete {
mutation := newUeMutation(c.config, OpDelete)
return &UeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *UeClient) DeleteOne(u *Ue) *UeDeleteOne {
return c.DeleteOneID(u.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *UeClient) DeleteOneID(id int) *UeDeleteOne {
builder := c.Delete().Where(ue.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &UeDeleteOne{builder}
}
// Query returns a query builder for Ue.
func (c *UeClient) Query() *UeQuery {
return &UeQuery{
config: c.config,
ctx: &QueryContext{Type: TypeUe},
inters: c.Interceptors(),
}
}
// Get returns a Ue entity by its id.
func (c *UeClient) Get(ctx context.Context, id int) (*Ue, error) {
return c.Query().Where(ue.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *UeClient) GetX(ctx context.Context, id int) *Ue {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryOwner queries the owner edge of a Ue.
func (c *UeClient) QueryOwner(u *Ue) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := u.ID
step := sqlgraph.NewStep(
sqlgraph.From(ue.Table, ue.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, ue.OwnerTable, ue.OwnerColumn),
)
fromV = sqlgraph.Neighbors(u.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *UeClient) Hooks() []Hook {
return c.hooks.Ue
}
// Interceptors returns the client interceptors.
func (c *UeClient) Interceptors() []Interceptor {
return c.inters.Ue
}
func (c *UeClient) mutate(ctx context.Context, m *UeMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&UeCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&UeUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&UeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&UeDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Ue 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
}
// QueryUe queries the ue edge of a User.
func (c *UserClient) QueryUe(u *User) *UeQuery {
query := (&UeClient{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(ue.Table, ue.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, user.UeTable, user.UeColumn),
)
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, Ue, User []ent.Hook
}
inters struct {
Card, Group, Ue, User []ent.Interceptor
}
)

614
ent/ent.go Normal file
View File

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

86
ent/entc.go Normal file
View File

@@ -0,0 +1,86 @@
//go:build ignore
package main
import (
"log"
"ariga.io/ogent"
"entgo.io/contrib/entoas"
"entgo.io/ent/entc"
"entgo.io/ent/entc/gen"
"github.com/ogen-go/ogen"
)
func main() {
spec := new(ogen.Spec)
//oas, err := entoas.NewExtension(entoas.Spec(spec))
oas, err := entoas.NewExtension(
entoas.Spec(spec),
entoas.Mutations(func(_ *gen.Graph, spec *ogen.Spec) error {
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("Card").
AddResponse("204", ogen.NewResponse().SetDescription("Item marked as done")),
).
AddParameters(ogen.NewParameter().
InPath().
SetName("id").
SetRequired(true).
SetSchema(ogen.Int()),
),
)
return nil
}),
// entoas.Mutations(func(_ *gen.Graph, spec *ogen.Spec) error {
// spec.AddPathItem(
// "/syui",
// ogen.NewPathItem().
// SetGet(
// ogen.NewOperation().
// SetOperationID("customReadUser").
//
// AddResponse("204", ogen.NewResponse().SetDescription("Item marked as done")),
// ),
// )
// return nil
// }),
entoas.Mutations(func(_ *gen.Graph, spec *ogen.Spec) error {
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("Card").
AddResponse("204", ogen.NewResponse().SetDescription("Item marked as done")),
//AddResponse("204", ogen.NewResponse().SetDescription("Item marked as done").SetSchema("test")),
).
AddParameters(ogen.NewParameter().
InPath().
SetName("id").
SetRequired(true).
SetSchema(ogen.Int()),
),
)
return nil
}),
)
if err != nil {
log.Fatalf("creating entoas extension: %v", err)
}
ogent, err := ogent.NewExtension(spec)
if err != nil {
log.Fatalf("creating ogent extension: %v", err)
}
err = entc.Generate("./schema", &gen.Config{}, entc.Extensions(ogent, oas))
if err != nil {
log.Fatalf("running ent codegen: %v", err)
}
}

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

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

3
ent/generate.go Normal file
View File

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

139
ent/group.go Normal file
View File

@@ -0,0 +1,139 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"api/ent/group"
"fmt"
"strings"
"entgo.io/ent"
"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"`
// Password holds the value of the "password" field.
Password string `json:"-"`
// 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"`
selectValues sql.SelectValues
}
// 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, group.FieldPassword:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
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
}
case group.FieldPassword:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field password", values[i])
} else if value.Valid {
gr.Password = value.String
}
default:
gr.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Group.
// This includes values selected through modifiers, order, etc.
func (gr *Group) Value(name string) (ent.Value, error) {
return gr.selectValues.Get(name)
}
// 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.WriteString(", ")
builder.WriteString("password=<sensitive>")
builder.WriteByte(')')
return builder.String()
}
// Groups is a parsable slice of Group.
type Groups []*Group

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

@@ -0,0 +1,91 @@
// Code generated by ent, DO NOT EDIT.
package group
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
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"
// FieldPassword holds the string denoting the password field in the database.
FieldPassword = "password"
// 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,
FieldPassword,
}
// 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 (
// PasswordValidator is a validator for the "password" field. It is called by the builders before save.
PasswordValidator func(string) error
)
// OrderOption defines the ordering options for the Group queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByPassword orders the results by the password field.
func ByPassword(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPassword, opts...).ToFunc()
}
// ByUsersCount orders the results by users count.
func ByUsersCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newUsersStep(), opts...)
}
}
// ByUsers orders the results by users terms.
func ByUsers(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUsersStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newUsersStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UsersInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, UsersTable, UsersColumn),
)
}

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

@@ -0,0 +1,250 @@
// Code generated by ent, DO NOT EDIT.
package group
import (
"api/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))
}
// Password applies equality check predicate on the "password" field. It's identical to PasswordEQ.
func Password(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldPassword, 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))
}
// PasswordEQ applies the EQ predicate on the "password" field.
func PasswordEQ(v string) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldPassword, v))
}
// PasswordNEQ applies the NEQ predicate on the "password" field.
func PasswordNEQ(v string) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldPassword, v))
}
// PasswordIn applies the In predicate on the "password" field.
func PasswordIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldIn(FieldPassword, vs...))
}
// PasswordNotIn applies the NotIn predicate on the "password" field.
func PasswordNotIn(vs ...string) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldPassword, vs...))
}
// PasswordGT applies the GT predicate on the "password" field.
func PasswordGT(v string) predicate.Group {
return predicate.Group(sql.FieldGT(FieldPassword, v))
}
// PasswordGTE applies the GTE predicate on the "password" field.
func PasswordGTE(v string) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldPassword, v))
}
// PasswordLT applies the LT predicate on the "password" field.
func PasswordLT(v string) predicate.Group {
return predicate.Group(sql.FieldLT(FieldPassword, v))
}
// PasswordLTE applies the LTE predicate on the "password" field.
func PasswordLTE(v string) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldPassword, v))
}
// PasswordContains applies the Contains predicate on the "password" field.
func PasswordContains(v string) predicate.Group {
return predicate.Group(sql.FieldContains(FieldPassword, v))
}
// PasswordHasPrefix applies the HasPrefix predicate on the "password" field.
func PasswordHasPrefix(v string) predicate.Group {
return predicate.Group(sql.FieldHasPrefix(FieldPassword, v))
}
// PasswordHasSuffix applies the HasSuffix predicate on the "password" field.
func PasswordHasSuffix(v string) predicate.Group {
return predicate.Group(sql.FieldHasSuffix(FieldPassword, v))
}
// PasswordEqualFold applies the EqualFold predicate on the "password" field.
func PasswordEqualFold(v string) predicate.Group {
return predicate.Group(sql.FieldEqualFold(FieldPassword, v))
}
// PasswordContainsFold applies the ContainsFold predicate on the "password" field.
func PasswordContainsFold(v string) predicate.Group {
return predicate.Group(sql.FieldContainsFold(FieldPassword, 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 := newUsersStep()
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())
})
}

229
ent/group_create.go Normal file
View File

@@ -0,0 +1,229 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"api/ent/group"
"api/ent/user"
"context"
"errors"
"fmt"
"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
}
// SetPassword sets the "password" field.
func (gc *GroupCreate) SetPassword(s string) *GroupCreate {
gc.mutation.SetPassword(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"`)}
}
if _, ok := gc.mutation.Password(); !ok {
return &ValidationError{Name: "password", err: errors.New(`ent: missing required field "Group.password"`)}
}
if v, ok := gc.mutation.Password(); ok {
if err := group.PasswordValidator(v); err != nil {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "Group.password": %w`, err)}
}
}
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 value, ok := gc.mutation.Password(); ok {
_spec.SetField(group.FieldPassword, field.TypeString, value)
_node.Password = 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.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
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
var err error
nodes[i], specs[i] = builder.createSpec()
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 (
"api/ent/group"
"api/ent/predicate"
"context"
"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 (
"api/ent/group"
"api/ent/predicate"
"api/ent/user"
"context"
"database/sql/driver"
"fmt"
"math"
"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 []group.OrderOption
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 ...group.OrderOption) *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([]group.OrderOption{}, 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(s.C(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 referenced 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)
}

356
ent/group_update.go Normal file
View File

@@ -0,0 +1,356 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"api/ent/group"
"api/ent/predicate"
"api/ent/user"
"context"
"errors"
"fmt"
"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.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_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.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
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.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if 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.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_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.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
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.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &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
}

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

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

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

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

View File

@@ -0,0 +1,12 @@
-- Create "cards" table
CREATE TABLE `cards` (`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT, `password` text NOT NULL, `card` integer NULL, `status` text NULL, `cp` integer NULL, `url` text NULL DEFAULT 'https://card.syui.ai', `created_at` datetime NULL, `user_card` integer NOT NULL, CONSTRAINT `cards_users_card` FOREIGN KEY (`user_card`) REFERENCES `users` (`id`) ON DELETE NO ACTION);
-- Create "groups" table
CREATE TABLE `groups` (`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT, `name` text NOT NULL, `password` text NOT NULL);
-- Create index "group_name" to table: "groups"
CREATE UNIQUE INDEX `group_name` ON `groups` (`name`);
-- Create "users" table
CREATE TABLE `users` (`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT, `username` text NOT NULL, `password` text NOT NULL, `created_at` datetime NULL, `updated_at` datetime NULL, `next` text NULL DEFAULT '20230405', `group_users` integer NULL, CONSTRAINT `users_groups_users` FOREIGN KEY (`group_users`) REFERENCES `groups` (`id`) ON DELETE SET NULL);
-- Create index "users_username_key" to table: "users"
CREATE UNIQUE INDEX `users_username_key` ON `users` (`username`);
-- Create index "user_username" to table: "users"
CREATE UNIQUE INDEX `user_username` ON `users` (`username`);

View File

@@ -0,0 +1,2 @@
h1:GU79ffcSbQHeq4BLGuuAdObBOt0WLTcsQx+AucxEqkA=
20230405104340_migration_name.sql h1:vlsZT8ob1qpLmBAGPqNBBG/iFact7wy1pb27tAavvRU=

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

@@ -0,0 +1,183 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// CardsColumns holds the columns for the "cards" table.
CardsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "password", Type: field.TypeString},
{Name: "card", Type: field.TypeInt, Nullable: true},
{Name: "skill", Type: field.TypeString, Nullable: true},
{Name: "status", Type: field.TypeString, Nullable: true},
{Name: "token", 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: "count", Type: field.TypeInt, Nullable: true},
{Name: "author", Type: field.TypeString, Nullable: true, Default: "yui"},
{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[11]},
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},
{Name: "password", 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]},
},
},
}
// UesColumns holds the columns for the "ues" table.
UesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "limit", Type: field.TypeBool, Nullable: true, Default: false},
{Name: "limit_boss", Type: field.TypeBool, Nullable: true, Default: false},
{Name: "limit_item", Type: field.TypeBool, Nullable: true, Default: false},
{Name: "password", Type: field.TypeString},
{Name: "lv", Type: field.TypeInt, Nullable: true},
{Name: "lv_point", Type: field.TypeInt, Nullable: true},
{Name: "model", Type: field.TypeInt, Nullable: true},
{Name: "sword", Type: field.TypeInt, Nullable: true},
{Name: "card", Type: field.TypeInt, Nullable: true},
{Name: "mode", Type: field.TypeString, Nullable: true},
{Name: "token", Type: field.TypeString, Nullable: true},
{Name: "cp", Type: field.TypeInt, Nullable: true},
{Name: "count", Type: field.TypeInt, Nullable: true},
{Name: "location_x", Type: field.TypeInt, Nullable: true},
{Name: "location_y", Type: field.TypeInt, Nullable: true},
{Name: "location_z", Type: field.TypeInt, Nullable: true},
{Name: "location_n", Type: field.TypeInt, Nullable: true},
{Name: "author", Type: field.TypeString, Nullable: true},
{Name: "created_at", Type: field.TypeTime, Nullable: true},
{Name: "user_ue", Type: field.TypeInt},
}
// UesTable holds the schema information for the "ues" table.
UesTable = &schema.Table{
Name: "ues",
Columns: UesColumns,
PrimaryKey: []*schema.Column{UesColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "ues_users_ue",
Columns: []*schema.Column{UesColumns[20]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
},
}
// UsersColumns holds the columns for the "users" table.
UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "username", Type: field.TypeString, Unique: true, Size: 100},
{Name: "did", Type: field.TypeString, Nullable: true},
{Name: "member", Type: field.TypeBool, Nullable: true, Default: false},
{Name: "book", Type: field.TypeBool, Nullable: true, Default: false},
{Name: "manga", Type: field.TypeBool, Nullable: true, Default: false},
{Name: "badge", Type: field.TypeBool, Nullable: true, Default: false},
{Name: "bsky", Type: field.TypeBool, Nullable: true, Default: false},
{Name: "mastodon", Type: field.TypeBool, Nullable: true, Default: true},
{Name: "delete", Type: field.TypeBool, Nullable: true, Default: false},
{Name: "handle", Type: field.TypeBool, Nullable: true, Default: false},
{Name: "token", Type: field.TypeString, Nullable: true},
{Name: "password", Type: field.TypeString},
{Name: "created_at", Type: field.TypeTime, Nullable: true},
{Name: "updated_at", Type: field.TypeTime, Nullable: true},
{Name: "raid_at", Type: field.TypeTime, Nullable: true},
{Name: "server_at", Type: field.TypeTime, Nullable: true},
{Name: "egg_at", Type: field.TypeTime, Nullable: true},
{Name: "luck", Type: field.TypeInt, Nullable: true},
{Name: "luck_at", Type: field.TypeTime, Nullable: true},
{Name: "like", Type: field.TypeInt, Nullable: true},
{Name: "like_rank", Type: field.TypeInt, Nullable: true},
{Name: "like_at", Type: field.TypeTime, Nullable: true},
{Name: "fav", Type: field.TypeInt, Nullable: true},
{Name: "ten", Type: field.TypeBool, Nullable: true},
{Name: "ten_su", Type: field.TypeInt, Nullable: true},
{Name: "ten_kai", Type: field.TypeInt, Nullable: true},
{Name: "aiten", Type: field.TypeInt, Nullable: true},
{Name: "ten_card", Type: field.TypeString, Nullable: true},
{Name: "ten_delete", Type: field.TypeString, Nullable: true},
{Name: "ten_post", Type: field.TypeString, Nullable: true},
{Name: "ten_get", Type: field.TypeString, Nullable: true},
{Name: "ten_at", Type: field.TypeTime, Nullable: true},
{Name: "next", Type: field.TypeString, Nullable: true, Default: "20240221"},
{Name: "room", Type: field.TypeInt, Nullable: true},
{Name: "model", Type: field.TypeBool, Nullable: true},
{Name: "model_at", Type: field.TypeTime, Nullable: true},
{Name: "model_attack", Type: field.TypeInt, Nullable: true},
{Name: "model_limit", Type: field.TypeInt, Nullable: true},
{Name: "model_skill", Type: field.TypeInt, Nullable: true},
{Name: "model_mode", Type: field.TypeInt, Nullable: true},
{Name: "model_critical", Type: field.TypeInt, Nullable: true},
{Name: "model_critical_d", Type: field.TypeInt, Nullable: true},
{Name: "game", Type: field.TypeBool, Nullable: true, Default: false},
{Name: "game_test", Type: field.TypeBool, Nullable: true, Default: false},
{Name: "game_end", Type: field.TypeBool, Nullable: true, Default: false},
{Name: "game_account", Type: field.TypeBool, Nullable: true, Default: false},
{Name: "game_lv", Type: field.TypeInt, Nullable: true},
{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[48]},
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,
UesTable,
UsersTable,
}
)
func init() {
CardsTable.ForeignKeys[0].RefTable = UsersTable
UesTable.ForeignKeys[0].RefTable = UsersTable
UsersTable.ForeignKeys[0].RefTable = GroupsTable
}

8109
ent/mutation.go Normal file

File diff suppressed because it is too large Load Diff

277
ent/ogent/oas_cfg_gen.go Normal file
View File

@@ -0,0 +1,277 @@
// Code generated by ogen, DO NOT EDIT.
package ogent
import (
"net/http"
"go.opentelemetry.io/otel"
"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"
)
var (
// Allocate option closure once.
clientSpanKind = trace.WithSpanKind(trace.SpanKindClient)
// Allocate option closure once.
serverSpanKind = trace.WithSpanKind(trace.SpanKindServer)
)
type (
optionFunc[C any] func(*C)
otelOptionFunc func(*otelConfig)
)
type otelConfig struct {
TracerProvider trace.TracerProvider
Tracer trace.Tracer
MeterProvider metric.MeterProvider
Meter metric.Meter
}
func (cfg *otelConfig) initOTEL() {
if cfg.TracerProvider == nil {
cfg.TracerProvider = otel.GetTracerProvider()
}
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 baseServer struct {
cfg serverConfig
requests instrument.Int64Counter
errors instrument.Int64Counter
duration instrument.Int64Histogram
}
func (s baseServer) notFound(w http.ResponseWriter, r *http.Request) {
s.cfg.NotFound(w, r)
}
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 otelOptionFunc(func(cfg *otelConfig) {
if provider != nil {
cfg.TracerProvider = provider
}
})
}
// WithMeterProvider specifies a meter provider to use for creating a meter.
//
// If none is specified, the metric.NewNoopMeterProvider is used.
func WithMeterProvider(provider metric.MeterProvider) Option {
return otelOptionFunc(func(cfg *otelConfig) {
if provider != nil {
cfg.MeterProvider = provider
}
})
}
// WithClient specifies http client to use.
func WithClient(client ht.Client) ClientOption {
return optionFunc[clientConfig](func(cfg *clientConfig) {
if client != nil {
cfg.Client = client
}
})
}
// 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
}
})
}

2459
ent/ogent/oas_client_gen.go Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,102 @@
// Code generated by ogen, DO NOT EDIT.
package ogent
type CreateCardRes interface {
createCardRes()
}
type CreateGroupRes interface {
createGroupRes()
}
type CreateUeRes interface {
createUeRes()
}
type CreateUserRes interface {
createUserRes()
}
type DeleteCardRes interface {
deleteCardRes()
}
type DeleteGroupRes interface {
deleteGroupRes()
}
type DeleteUeRes interface {
deleteUeRes()
}
type DeleteUserRes interface {
deleteUserRes()
}
type ListCardRes interface {
listCardRes()
}
type ListGroupRes interface {
listGroupRes()
}
type ListGroupUsersRes interface {
listGroupUsersRes()
}
type ListUeRes interface {
listUeRes()
}
type ListUserCardRes interface {
listUserCardRes()
}
type ListUserRes interface {
listUserRes()
}
type ListUserUeRes interface {
listUserUeRes()
}
type ReadCardOwnerRes interface {
readCardOwnerRes()
}
type ReadCardRes interface {
readCardRes()
}
type ReadGroupRes interface {
readGroupRes()
}
type ReadUeOwnerRes interface {
readUeOwnerRes()
}
type ReadUeRes interface {
readUeRes()
}
type ReadUserRes interface {
readUserRes()
}
type UpdateCardRes interface {
updateCardRes()
}
type UpdateGroupRes interface {
updateGroupRes()
}
type UpdateUeRes interface {
updateUeRes()
}
type UpdateUserRes interface {
updateUserRes()
}

13968
ent/ogent/oas_json_gen.go Normal file

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

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,520 @@
// 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) decodeCreateUeRequest(r *http.Request) (
req *CreateUeReq,
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 CreateUeReq
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) decodeUpdateUeRequest(r *http.Request) (
req *UpdateUeReq,
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 UpdateUeReq
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,124 @@
// 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 encodeCreateUeRequest(
req *CreateUeReq,
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 encodeUpdateUeRequest(
req *UpdateUeReq,
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
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

1034
ent/ogent/oas_router_gen.go Normal file

File diff suppressed because it is too large Load Diff

7480
ent/ogent/oas_schemas_gen.go Normal file

File diff suppressed because it is too large Load Diff

192
ent/ogent/oas_server_gen.go Normal file
View File

@@ -0,0 +1,192 @@
// Code generated by ogen, DO NOT EDIT.
package ogent
import (
"context"
)
// Handler handles operations described by OpenAPI v3 specification.
type Handler interface {
// CreateCard implements createCard operation.
//
// 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)
// CreateUe implements createUe operation.
//
// Creates a new Ue and persists it to storage.
//
// POST /ues
CreateUe(ctx context.Context, req *CreateUeReq) (CreateUeRes, error)
// CreateUser implements createUser operation.
//
// Creates a new User and persists it to storage.
//
// POST /users
CreateUser(ctx context.Context, req *CreateUserReq) (CreateUserRes, error)
// DeleteCard implements deleteCard operation.
//
// 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)
// DeleteUe implements deleteUe operation.
//
// Deletes the Ue with the requested ID.
//
// DELETE /ues/{id}
DeleteUe(ctx context.Context, params DeleteUeParams) (DeleteUeRes, error)
// DeleteUser implements deleteUser operation.
//
// Deletes the User with the requested ID.
//
// DELETE /users/{id}
DeleteUser(ctx context.Context, params DeleteUserParams) (DeleteUserRes, error)
// DrawDone implements drawDone operation.
//
// Draws a card item as done.
//
// PUT /cards/{id}/d
DrawDone(ctx context.Context, params DrawDoneParams) error
// DrawStart implements drawStart 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)
// ListUe implements listUe operation.
//
// List Ues.
//
// GET /ues
ListUe(ctx context.Context, params ListUeParams) (ListUeRes, error)
// ListUser implements listUser operation.
//
// List Users.
//
// GET /users
ListUser(ctx context.Context, params ListUserParams) (ListUserRes, error)
// ListUserCard implements listUserCard operation.
//
// List attached Cards.
//
// GET /users/{id}/card
ListUserCard(ctx context.Context, params ListUserCardParams) (ListUserCardRes, error)
// ListUserUe implements listUserUe operation.
//
// List attached Ues.
//
// GET /users/{id}/ue
ListUserUe(ctx context.Context, params ListUserUeParams) (ListUserUeRes, 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)
// ReadUe implements readUe operation.
//
// Finds the Ue with the requested ID and returns it.
//
// GET /ues/{id}
ReadUe(ctx context.Context, params ReadUeParams) (ReadUeRes, error)
// ReadUeOwner implements readUeOwner operation.
//
// Find the attached User of the Ue with the given ID.
//
// GET /ues/{id}/owner
ReadUeOwner(ctx context.Context, params ReadUeOwnerParams) (ReadUeOwnerRes, error)
// ReadUser implements readUser operation.
//
// Finds the User with the requested ID and returns it.
//
// GET /users/{id}
ReadUser(ctx context.Context, params ReadUserParams) (ReadUserRes, error)
// UpdateCard implements updateCard operation.
//
// 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)
// UpdateUe implements updateUe operation.
//
// Updates a Ue and persists changes to storage.
//
// PATCH /ues/{id}
UpdateUe(ctx context.Context, req *UpdateUeReq, params UpdateUeParams) (UpdateUeRes, error)
// UpdateUser implements updateUser operation.
//
// Updates a User and persists changes to storage.
//
// PATCH /users/{id}
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
baseServer
}
// 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,
baseServer: s,
}, nil
}

View File

@@ -0,0 +1,257 @@
// Code generated by ogen, DO NOT EDIT.
package ogent
import (
"context"
ht "github.com/ogen-go/ogen/http"
)
// UnimplementedHandler is no-op Handler which returns http.ErrNotImplemented.
type UnimplementedHandler struct{}
var _ Handler = UnimplementedHandler{}
// CreateCard implements createCard operation.
//
// Creates a new Card and persists it to storage.
//
// POST /cards
func (UnimplementedHandler) CreateCard(ctx context.Context, req *CreateCardReq) (r CreateCardRes, _ error) {
return r, ht.ErrNotImplemented
}
// CreateGroup implements createGroup operation.
//
// 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
}
// CreateUe implements createUe operation.
//
// Creates a new Ue and persists it to storage.
//
// POST /ues
func (UnimplementedHandler) CreateUe(ctx context.Context, req *CreateUeReq) (r CreateUeRes, _ 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
}
// DeleteUe implements deleteUe operation.
//
// Deletes the Ue with the requested ID.
//
// DELETE /ues/{id}
func (UnimplementedHandler) DeleteUe(ctx context.Context, params DeleteUeParams) (r DeleteUeRes, _ error) {
return r, ht.ErrNotImplemented
}
// DeleteUser implements deleteUser operation.
//
// Deletes the User with the requested ID.
//
// DELETE /users/{id}
func (UnimplementedHandler) DeleteUser(ctx context.Context, params DeleteUserParams) (r DeleteUserRes, _ error) {
return r, ht.ErrNotImplemented
}
// DrawDone implements drawDone operation.
//
// 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.
//
// 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
}
// 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
}
// ListUe implements listUe operation.
//
// List Ues.
//
// GET /ues
func (UnimplementedHandler) ListUe(ctx context.Context, params ListUeParams) (r ListUeRes, _ error) {
return r, ht.ErrNotImplemented
}
// ListUser implements listUser operation.
//
// List Users.
//
// GET /users
func (UnimplementedHandler) ListUser(ctx context.Context, params ListUserParams) (r ListUserRes, _ error) {
return r, ht.ErrNotImplemented
}
// ListUserCard implements listUserCard operation.
//
// List attached Cards.
//
// GET /users/{id}/card
func (UnimplementedHandler) ListUserCard(ctx context.Context, params ListUserCardParams) (r ListUserCardRes, _ error) {
return r, ht.ErrNotImplemented
}
// ListUserUe implements listUserUe operation.
//
// List attached Ues.
//
// GET /users/{id}/ue
func (UnimplementedHandler) ListUserUe(ctx context.Context, params ListUserUeParams) (r ListUserUeRes, _ 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
}
// ReadUe implements readUe operation.
//
// Finds the Ue with the requested ID and returns it.
//
// GET /ues/{id}
func (UnimplementedHandler) ReadUe(ctx context.Context, params ReadUeParams) (r ReadUeRes, _ error) {
return r, ht.ErrNotImplemented
}
// ReadUeOwner implements readUeOwner operation.
//
// Find the attached User of the Ue with the given ID.
//
// GET /ues/{id}/owner
func (UnimplementedHandler) ReadUeOwner(ctx context.Context, params ReadUeOwnerParams) (r ReadUeOwnerRes, _ error) {
return r, ht.ErrNotImplemented
}
// ReadUser implements readUser operation.
//
// Finds the User with the requested ID and returns it.
//
// GET /users/{id}
func (UnimplementedHandler) ReadUser(ctx context.Context, params ReadUserParams) (r ReadUserRes, _ error) {
return r, ht.ErrNotImplemented
}
// UpdateCard implements updateCard operation.
//
// Updates a Card and persists changes to storage.
//
// 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
}
// UpdateUe implements updateUe operation.
//
// Updates a Ue and persists changes to storage.
//
// PATCH /ues/{id}
func (UnimplementedHandler) UpdateUe(ctx context.Context, req *UpdateUeReq, params UpdateUeParams) (r UpdateUeRes, _ 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

@@ -0,0 +1,50 @@
// Code generated by ogen, DO NOT EDIT.
package ogent
import (
"github.com/go-faster/errors"
)
func (s ListCardOKApplicationJSON) Validate() error {
if s == nil {
return errors.New("nil is invalid value")
}
return nil
}
func (s ListGroupOKApplicationJSON) Validate() error {
if s == nil {
return errors.New("nil is invalid value")
}
return nil
}
func (s ListGroupUsersOKApplicationJSON) Validate() error {
if s == nil {
return errors.New("nil is invalid value")
}
return nil
}
func (s ListUeOKApplicationJSON) Validate() error {
if s == nil {
return errors.New("nil is invalid value")
}
return nil
}
func (s ListUserCardOKApplicationJSON) Validate() error {
if s == nil {
return errors.New("nil is invalid value")
}
return nil
}
func (s ListUserOKApplicationJSON) Validate() error {
if s == nil {
return errors.New("nil is invalid value")
}
return nil
}
func (s ListUserUeOKApplicationJSON) Validate() error {
if s == nil {
return errors.New("nil is invalid value")
}
return nil
}

1320
ent/ogent/ogent.go Normal file

File diff suppressed because it is too large Load Diff

1016
ent/ogent/responses.go Normal file

File diff suppressed because it is too large Load Diff

3906
ent/openapi.json Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,19 @@
// Code generated by ent, DO NOT EDIT.
package predicate
import (
"entgo.io/ent/dialect/sql"
)
// 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)
// Ue is the predicate function for ue builders.
type Ue func(*sql.Selector)
// User is the predicate function for user builders.
type User func(*sql.Selector)

197
ent/runtime.go Normal file
View File

@@ -0,0 +1,197 @@
// +build tools
// +build tools
// +build tools
// +build tools
// +build tools
// Code generated by ent, DO NOT EDIT.
package ent
import (
"api/ent/card"
"api/ent/group"
"api/ent/schema"
"api/ent/ue"
"api/ent/user"
"time"
)
// The init function reads all schema descriptors with runtime code
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
cardFields := schema.Card{}.Fields()
_ = cardFields
// cardDescPassword is the schema descriptor for password field.
cardDescPassword := cardFields[0].Descriptor()
// card.PasswordValidator is a validator for the "password" field. It is called by the builders before save.
card.PasswordValidator = cardDescPassword.Validators[0].(func(string) error)
// cardDescCard is the schema descriptor for card field.
cardDescCard := cardFields[1].Descriptor()
// card.DefaultCard holds the default value on creation for the card field.
card.DefaultCard = cardDescCard.Default.(func() int)
// cardDescSkill is the schema descriptor for skill field.
cardDescSkill := cardFields[2].Descriptor()
// card.DefaultSkill holds the default value on creation for the skill field.
card.DefaultSkill = cardDescSkill.Default.(func() string)
// cardDescStatus is the schema descriptor for status field.
cardDescStatus := cardFields[3].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[5].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[6].Descriptor()
// card.DefaultURL holds the default value on creation for the url field.
card.DefaultURL = cardDescURL.Default.(string)
// cardDescAuthor is the schema descriptor for author field.
cardDescAuthor := cardFields[8].Descriptor()
// card.DefaultAuthor holds the default value on creation for the author field.
card.DefaultAuthor = cardDescAuthor.Default.(string)
// cardDescCreatedAt is the schema descriptor for created_at field.
cardDescCreatedAt := cardFields[9].Descriptor()
// card.DefaultCreatedAt holds the default value on creation for the created_at field.
card.DefaultCreatedAt = cardDescCreatedAt.Default.(func() time.Time)
groupFields := schema.Group{}.Fields()
_ = groupFields
// groupDescPassword is the schema descriptor for password field.
groupDescPassword := groupFields[1].Descriptor()
// group.PasswordValidator is a validator for the "password" field. It is called by the builders before save.
group.PasswordValidator = groupDescPassword.Validators[0].(func(string) error)
ueFields := schema.Ue{}.Fields()
_ = ueFields
// ueDescLimit is the schema descriptor for limit field.
ueDescLimit := ueFields[0].Descriptor()
// ue.DefaultLimit holds the default value on creation for the limit field.
ue.DefaultLimit = ueDescLimit.Default.(bool)
// ueDescLimitBoss is the schema descriptor for limit_boss field.
ueDescLimitBoss := ueFields[1].Descriptor()
// ue.DefaultLimitBoss holds the default value on creation for the limit_boss field.
ue.DefaultLimitBoss = ueDescLimitBoss.Default.(bool)
// ueDescLimitItem is the schema descriptor for limit_item field.
ueDescLimitItem := ueFields[2].Descriptor()
// ue.DefaultLimitItem holds the default value on creation for the limit_item field.
ue.DefaultLimitItem = ueDescLimitItem.Default.(bool)
// ueDescPassword is the schema descriptor for password field.
ueDescPassword := ueFields[3].Descriptor()
// ue.PasswordValidator is a validator for the "password" field. It is called by the builders before save.
ue.PasswordValidator = ueDescPassword.Validators[0].(func(string) error)
// ueDescCreatedAt is the schema descriptor for created_at field.
ueDescCreatedAt := ueFields[18].Descriptor()
// ue.DefaultCreatedAt holds the default value on creation for the created_at field.
ue.DefaultCreatedAt = ueDescCreatedAt.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),
}
return func(username string) error {
for _, fn := range fns {
if err := fn(username); err != nil {
return err
}
}
return nil
}
}()
// userDescMember is the schema descriptor for member field.
userDescMember := userFields[2].Descriptor()
// user.DefaultMember holds the default value on creation for the member field.
user.DefaultMember = userDescMember.Default.(bool)
// userDescBook is the schema descriptor for book field.
userDescBook := userFields[3].Descriptor()
// user.DefaultBook holds the default value on creation for the book field.
user.DefaultBook = userDescBook.Default.(bool)
// userDescManga is the schema descriptor for manga field.
userDescManga := userFields[4].Descriptor()
// user.DefaultManga holds the default value on creation for the manga field.
user.DefaultManga = userDescManga.Default.(bool)
// userDescBadge is the schema descriptor for badge field.
userDescBadge := userFields[5].Descriptor()
// user.DefaultBadge holds the default value on creation for the badge field.
user.DefaultBadge = userDescBadge.Default.(bool)
// userDescBsky is the schema descriptor for bsky field.
userDescBsky := userFields[6].Descriptor()
// user.DefaultBsky holds the default value on creation for the bsky field.
user.DefaultBsky = userDescBsky.Default.(bool)
// userDescMastodon is the schema descriptor for mastodon field.
userDescMastodon := userFields[7].Descriptor()
// user.DefaultMastodon holds the default value on creation for the mastodon field.
user.DefaultMastodon = userDescMastodon.Default.(bool)
// userDescDelete is the schema descriptor for delete field.
userDescDelete := userFields[8].Descriptor()
// user.DefaultDelete holds the default value on creation for the delete field.
user.DefaultDelete = userDescDelete.Default.(bool)
// userDescHandle is the schema descriptor for handle field.
userDescHandle := userFields[9].Descriptor()
// user.DefaultHandle holds the default value on creation for the handle field.
user.DefaultHandle = userDescHandle.Default.(bool)
// userDescPassword is the schema descriptor for password field.
userDescPassword := userFields[11].Descriptor()
// user.PasswordValidator is a validator for the "password" field. It is called by the builders before save.
user.PasswordValidator = userDescPassword.Validators[0].(func(string) error)
// userDescCreatedAt is the schema descriptor for created_at field.
userDescCreatedAt := userFields[12].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[13].Descriptor()
// user.DefaultUpdatedAt holds the default value on creation for the updated_at field.
user.DefaultUpdatedAt = userDescUpdatedAt.Default.(func() time.Time)
// userDescRaidAt is the schema descriptor for raid_at field.
userDescRaidAt := userFields[14].Descriptor()
// user.DefaultRaidAt holds the default value on creation for the raid_at field.
user.DefaultRaidAt = userDescRaidAt.Default.(func() time.Time)
// userDescServerAt is the schema descriptor for server_at field.
userDescServerAt := userFields[15].Descriptor()
// user.DefaultServerAt holds the default value on creation for the server_at field.
user.DefaultServerAt = userDescServerAt.Default.(func() time.Time)
// userDescEggAt is the schema descriptor for egg_at field.
userDescEggAt := userFields[16].Descriptor()
// user.DefaultEggAt holds the default value on creation for the egg_at field.
user.DefaultEggAt = userDescEggAt.Default.(func() time.Time)
// userDescLuckAt is the schema descriptor for luck_at field.
userDescLuckAt := userFields[18].Descriptor()
// user.DefaultLuckAt holds the default value on creation for the luck_at field.
user.DefaultLuckAt = userDescLuckAt.Default.(func() time.Time)
// userDescLikeAt is the schema descriptor for like_at field.
userDescLikeAt := userFields[21].Descriptor()
// user.DefaultLikeAt holds the default value on creation for the like_at field.
user.DefaultLikeAt = userDescLikeAt.Default.(func() time.Time)
// userDescTenAt is the schema descriptor for ten_at field.
userDescTenAt := userFields[31].Descriptor()
// user.DefaultTenAt holds the default value on creation for the ten_at field.
user.DefaultTenAt = userDescTenAt.Default.(func() time.Time)
// userDescNext is the schema descriptor for next field.
userDescNext := userFields[32].Descriptor()
// user.DefaultNext holds the default value on creation for the next field.
user.DefaultNext = userDescNext.Default.(string)
// userDescModelAt is the schema descriptor for model_at field.
userDescModelAt := userFields[35].Descriptor()
// user.DefaultModelAt holds the default value on creation for the model_at field.
user.DefaultModelAt = userDescModelAt.Default.(func() time.Time)
// userDescGame is the schema descriptor for game field.
userDescGame := userFields[42].Descriptor()
// user.DefaultGame holds the default value on creation for the game field.
user.DefaultGame = userDescGame.Default.(bool)
// userDescGameTest is the schema descriptor for game_test field.
userDescGameTest := userFields[43].Descriptor()
// user.DefaultGameTest holds the default value on creation for the game_test field.
user.DefaultGameTest = userDescGameTest.Default.(bool)
// userDescGameEnd is the schema descriptor for game_end field.
userDescGameEnd := userFields[44].Descriptor()
// user.DefaultGameEnd holds the default value on creation for the game_end field.
user.DefaultGameEnd = userDescGameEnd.Default.(bool)
// userDescGameAccount is the schema descriptor for game_account field.
userDescGameAccount := userFields[45].Descriptor()
// user.DefaultGameAccount holds the default value on creation for the game_account field.
user.DefaultGameAccount = userDescGameAccount.Default.(bool)
}

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

@@ -0,0 +1,10 @@
// Code generated by ent, DO NOT EDIT.
package runtime
// The schema-stitching logic is generated in api/ent/runtime.go
const (
Version = "v0.12.2" // Version of ent codegen.
Sum = "h1:Ndl/JvCX76xCtUDlrUfMnOKBRodAtxE5yfGYxjbOxmM=" // Sum of ent codegen.
)

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

@@ -0,0 +1,161 @@
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 skill string
var cp int
func (Card) Fields() []ent.Field {
return []ent.Field{
field.String("password").
NotEmpty().
Immutable().
Sensitive(),
field.Int("card").
DefaultFunc(func() int {
rand.Seed(time.Now().UnixNano())
var a = rand.Intn(10)
if a == 1 {
card = rand.Intn(16)
} else {
card = 0
}
if card == 13 {
card = 29
}
// 2023/04/09 premium card id:15
if card == 15 {
card = 3
}
if card == 16 {
card = 4
}
if card == 17 {
card = 5
}
if card == 18 {
card = 6
}
//var card = rand.Intn(91)
return card
}).
Optional(),
field.String("skill").
DefaultFunc(func() string {
rand.Seed(time.Now().UnixNano())
var a = rand.Intn(12)
if a == 1 {
skill = "critical"
} else {
skill = "normal"
}
if card == 0 {
skill = "normal"
}
return skill
}).
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.String("token").
Optional().
Sensitive(),
field.Int("cp").
//Immutable().
DefaultFunc(func() int {
rand.Seed(time.Now().UnixNano())
var cp = 1 + rand.Intn(200)
if cp == 2 {
cp = 50 + rand.Intn(300)
}
if card >= 1 {
cp = 200 + cp + rand.Intn(500)
}
if super == "super" {
cp = 400 + cp + rand.Intn(700)
}
if skill == "critical" {
cp = 400 + cp + rand.Intn(700)
}
if card == 22 {
cp = 800 + cp + rand.Intn(1500)
}
if card == 25 {
cp = 0
}
return cp
}).
Optional(),
field.String("url").
Default(url).
Optional(),
field.Int("count").
Optional(),
field.String("author").
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(),
}
}

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

@@ -0,0 +1,40 @@
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"),
field.String("password").
NotEmpty().
Immutable().
Sensitive(),
}
}
// 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(),
}
}

95
ent/schema/ue.go Normal file
View File

@@ -0,0 +1,95 @@
package schema
import (
"time"
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
// Game holds the schema definition for the Game entity.
type Ue struct {
ent.Schema
}
func (Ue) Fields() []ent.Field {
return []ent.Field{
field.Bool("limit").
Default(false).
Optional(),
field.Bool("limit_boss").
Default(false).
Optional(),
field.Bool("limit_item").
Default(false).
Optional(),
field.String("password").
NotEmpty().
Immutable().
Sensitive(),
field.Int("lv").
Optional(),
field.Int("lv_point").
Optional(),
field.Int("model").
Optional(),
field.Int("sword").
Optional(),
field.Int("card").
Optional(),
field.String("mode").
Optional(),
field.String("token").
Optional().
Sensitive(),
field.Int("cp").
Optional(),
field.Int("count").
Optional(),
field.Int("location_x").
Optional(),
field.Int("location_y").
Optional(),
field.Int("location_z").
Optional(),
field.Int("location_n").
Optional(),
field.String("author").
Optional(),
field.Time("created_at").
Immutable().
Optional().
Default(func() time.Time {
return time.Now().In(jst)
}),
}
}
func (Ue) Edges() []ent.Edge {
return []ent.Edge{
edge.From("owner", User.Type).
Ref("ue").
Unique().
Required(),
}
}

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

@@ -0,0 +1,237 @@
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)
t := time.Now().AddDate(0, 0, -1).In(jst)
tt = t.Format("20060102")
return
}
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("username").
NotEmpty().
Immutable().
MaxLen(100).
//Match(regexp.MustCompile("[a-z]+$")).
Unique(),
field.String("did").
Optional(),
field.Bool("member").
Default(false).
Optional(),
field.Bool("book").
Default(false).
Optional(),
field.Bool("manga").
Default(false).
Optional(),
field.Bool("badge").
Default(false).
Optional(),
field.Bool("bsky").
Default(false).
Optional(),
field.Bool("mastodon").
Default(true).
Optional(),
field.Bool("delete").
Default(false).
Optional(),
field.Bool("handle").
Default(false).
Optional(),
field.String("token").
Optional().
Sensitive(),
field.String("password").
NotEmpty().
Immutable().
Sensitive(),
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.Time("raid_at").
Optional().
Default(func() time.Time {
return time.Now().In(jst)
}),
field.Time("server_at").
Optional().
Default(func() time.Time {
return time.Now().In(jst)
}),
field.Time("egg_at").
Optional().
Default(func() time.Time {
return time.Now().In(jst)
}),
field.Int("luck").
Optional(),
field.Time("luck_at").
Optional().
Default(func() time.Time {
return time.Now().In(jst)
}),
field.Int("like").
Optional(),
field.Int("like_rank").
Optional(),
field.Time("like_at").
Optional().
Default(func() time.Time {
return time.Now().In(jst)
}),
field.Int("fav").
Optional(),
field.Bool("ten").
Optional(),
field.Int("ten_su").
Optional(),
field.Int("ten_kai").
Optional(),
field.Int("aiten").
Optional(),
field.String("ten_card").
Optional(),
field.String("ten_delete").
Optional(),
field.String("ten_post").
Optional(),
field.String("ten_get").
Optional(),
field.Time("ten_at").
Optional().
Default(func() time.Time {
return time.Now().In(jst)
}),
field.String("next").
Default(Nextime()).
Optional(),
field.Int("room").
Optional(),
field.Bool("model").
Optional(),
field.Time("model_at").
Optional().
Default(func() time.Time {
return time.Now().In(jst)
}),
field.Int("model_attack").
Optional(),
field.Int("model_limit").
Optional(),
field.Int("model_skill").
Optional(),
field.Int("model_mode").
Optional(),
field.Int("model_critical").
Optional(),
field.Int("model_critical_d").
Optional(),
field.Bool("game").
Default(false).
Optional(),
field.Bool("game_test").
Default(false).
Optional(),
field.Bool("game_end").
Default(false).
Optional(),
field.Bool("game_account").
Default(false).
Optional(),
field.Int("game_lv").
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),
edge.To("ue", Ue.Type),
//Unique(),
}
}

219
ent/tx.go Normal file
View File

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

345
ent/ue.go Normal file
View File

@@ -0,0 +1,345 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"api/ent/ue"
"api/ent/user"
"fmt"
"strings"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
)
// Ue is the model entity for the Ue schema.
type Ue struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Limit holds the value of the "limit" field.
Limit bool `json:"limit,omitempty"`
// LimitBoss holds the value of the "limit_boss" field.
LimitBoss bool `json:"limit_boss,omitempty"`
// LimitItem holds the value of the "limit_item" field.
LimitItem bool `json:"limit_item,omitempty"`
// Password holds the value of the "password" field.
Password string `json:"-"`
// Lv holds the value of the "lv" field.
Lv int `json:"lv,omitempty"`
// LvPoint holds the value of the "lv_point" field.
LvPoint int `json:"lv_point,omitempty"`
// Model holds the value of the "model" field.
Model int `json:"model,omitempty"`
// Sword holds the value of the "sword" field.
Sword int `json:"sword,omitempty"`
// Card holds the value of the "card" field.
Card int `json:"card,omitempty"`
// Mode holds the value of the "mode" field.
Mode string `json:"mode,omitempty"`
// Token holds the value of the "token" field.
Token string `json:"-"`
// Cp holds the value of the "cp" field.
Cp int `json:"cp,omitempty"`
// Count holds the value of the "count" field.
Count int `json:"count,omitempty"`
// LocationX holds the value of the "location_x" field.
LocationX int `json:"location_x,omitempty"`
// LocationY holds the value of the "location_y" field.
LocationY int `json:"location_y,omitempty"`
// LocationZ holds the value of the "location_z" field.
LocationZ int `json:"location_z,omitempty"`
// LocationN holds the value of the "location_n" field.
LocationN int `json:"location_n,omitempty"`
// Author holds the value of the "author" field.
Author string `json:"author,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 UeQuery when eager-loading is set.
Edges UeEdges `json:"edges"`
user_ue *int
selectValues sql.SelectValues
}
// UeEdges holds the relations/edges for other nodes in the graph.
type UeEdges 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 UeEdges) 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 (*Ue) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case ue.FieldLimit, ue.FieldLimitBoss, ue.FieldLimitItem:
values[i] = new(sql.NullBool)
case ue.FieldID, ue.FieldLv, ue.FieldLvPoint, ue.FieldModel, ue.FieldSword, ue.FieldCard, ue.FieldCp, ue.FieldCount, ue.FieldLocationX, ue.FieldLocationY, ue.FieldLocationZ, ue.FieldLocationN:
values[i] = new(sql.NullInt64)
case ue.FieldPassword, ue.FieldMode, ue.FieldToken, ue.FieldAuthor:
values[i] = new(sql.NullString)
case ue.FieldCreatedAt:
values[i] = new(sql.NullTime)
case ue.ForeignKeys[0]: // user_ue
values[i] = new(sql.NullInt64)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Ue fields.
func (u *Ue) 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 ue.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 ue.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 ue.FieldLimitBoss:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field limit_boss", values[i])
} else if value.Valid {
u.LimitBoss = value.Bool
}
case ue.FieldLimitItem:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field limit_item", values[i])
} else if value.Valid {
u.LimitItem = value.Bool
}
case ue.FieldPassword:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field password", values[i])
} else if value.Valid {
u.Password = value.String
}
case ue.FieldLv:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field lv", values[i])
} else if value.Valid {
u.Lv = int(value.Int64)
}
case ue.FieldLvPoint:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field lv_point", values[i])
} else if value.Valid {
u.LvPoint = int(value.Int64)
}
case ue.FieldModel:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field model", values[i])
} else if value.Valid {
u.Model = int(value.Int64)
}
case ue.FieldSword:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field sword", values[i])
} else if value.Valid {
u.Sword = int(value.Int64)
}
case ue.FieldCard:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field card", values[i])
} else if value.Valid {
u.Card = int(value.Int64)
}
case ue.FieldMode:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field mode", values[i])
} else if value.Valid {
u.Mode = value.String
}
case ue.FieldToken:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field token", values[i])
} else if value.Valid {
u.Token = value.String
}
case ue.FieldCp:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field cp", values[i])
} else if value.Valid {
u.Cp = int(value.Int64)
}
case ue.FieldCount:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field count", values[i])
} else if value.Valid {
u.Count = int(value.Int64)
}
case ue.FieldLocationX:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field location_x", values[i])
} else if value.Valid {
u.LocationX = int(value.Int64)
}
case ue.FieldLocationY:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field location_y", values[i])
} else if value.Valid {
u.LocationY = int(value.Int64)
}
case ue.FieldLocationZ:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field location_z", values[i])
} else if value.Valid {
u.LocationZ = int(value.Int64)
}
case ue.FieldLocationN:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field location_n", values[i])
} else if value.Valid {
u.LocationN = int(value.Int64)
}
case ue.FieldAuthor:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field author", values[i])
} else if value.Valid {
u.Author = value.String
}
case ue.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 ue.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for edge-field user_ue", value)
} else if value.Valid {
u.user_ue = new(int)
*u.user_ue = int(value.Int64)
}
default:
u.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Ue.
// This includes values selected through modifiers, order, etc.
func (u *Ue) Value(name string) (ent.Value, error) {
return u.selectValues.Get(name)
}
// QueryOwner queries the "owner" edge of the Ue entity.
func (u *Ue) QueryOwner() *UserQuery {
return NewUeClient(u.config).QueryOwner(u)
}
// Update returns a builder for updating this Ue.
// Note that you need to call Ue.Unwrap() before calling this method if this Ue
// was returned from a transaction, and the transaction was committed or rolled back.
func (u *Ue) Update() *UeUpdateOne {
return NewUeClient(u.config).UpdateOne(u)
}
// Unwrap unwraps the Ue 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 *Ue) Unwrap() *Ue {
_tx, ok := u.config.driver.(*txDriver)
if !ok {
panic("ent: Ue is not a transactional entity")
}
u.config.driver = _tx.drv
return u
}
// String implements the fmt.Stringer.
func (u *Ue) String() string {
var builder strings.Builder
builder.WriteString("Ue(")
builder.WriteString(fmt.Sprintf("id=%v, ", u.ID))
builder.WriteString("limit=")
builder.WriteString(fmt.Sprintf("%v", u.Limit))
builder.WriteString(", ")
builder.WriteString("limit_boss=")
builder.WriteString(fmt.Sprintf("%v", u.LimitBoss))
builder.WriteString(", ")
builder.WriteString("limit_item=")
builder.WriteString(fmt.Sprintf("%v", u.LimitItem))
builder.WriteString(", ")
builder.WriteString("password=<sensitive>")
builder.WriteString(", ")
builder.WriteString("lv=")
builder.WriteString(fmt.Sprintf("%v", u.Lv))
builder.WriteString(", ")
builder.WriteString("lv_point=")
builder.WriteString(fmt.Sprintf("%v", u.LvPoint))
builder.WriteString(", ")
builder.WriteString("model=")
builder.WriteString(fmt.Sprintf("%v", u.Model))
builder.WriteString(", ")
builder.WriteString("sword=")
builder.WriteString(fmt.Sprintf("%v", u.Sword))
builder.WriteString(", ")
builder.WriteString("card=")
builder.WriteString(fmt.Sprintf("%v", u.Card))
builder.WriteString(", ")
builder.WriteString("mode=")
builder.WriteString(u.Mode)
builder.WriteString(", ")
builder.WriteString("token=<sensitive>")
builder.WriteString(", ")
builder.WriteString("cp=")
builder.WriteString(fmt.Sprintf("%v", u.Cp))
builder.WriteString(", ")
builder.WriteString("count=")
builder.WriteString(fmt.Sprintf("%v", u.Count))
builder.WriteString(", ")
builder.WriteString("location_x=")
builder.WriteString(fmt.Sprintf("%v", u.LocationX))
builder.WriteString(", ")
builder.WriteString("location_y=")
builder.WriteString(fmt.Sprintf("%v", u.LocationY))
builder.WriteString(", ")
builder.WriteString("location_z=")
builder.WriteString(fmt.Sprintf("%v", u.LocationZ))
builder.WriteString(", ")
builder.WriteString("location_n=")
builder.WriteString(fmt.Sprintf("%v", u.LocationN))
builder.WriteString(", ")
builder.WriteString("author=")
builder.WriteString(u.Author)
builder.WriteString(", ")
builder.WriteString("created_at=")
builder.WriteString(u.CreatedAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// Ues is a parsable slice of Ue.
type Ues []*Ue

241
ent/ue/ue.go Normal file
View File

@@ -0,0 +1,241 @@
// Code generated by ent, DO NOT EDIT.
package ue
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the ue type in the database.
Label = "ue"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldLimit holds the string denoting the limit field in the database.
FieldLimit = "limit"
// FieldLimitBoss holds the string denoting the limit_boss field in the database.
FieldLimitBoss = "limit_boss"
// FieldLimitItem holds the string denoting the limit_item field in the database.
FieldLimitItem = "limit_item"
// FieldPassword holds the string denoting the password field in the database.
FieldPassword = "password"
// FieldLv holds the string denoting the lv field in the database.
FieldLv = "lv"
// FieldLvPoint holds the string denoting the lv_point field in the database.
FieldLvPoint = "lv_point"
// FieldModel holds the string denoting the model field in the database.
FieldModel = "model"
// FieldSword holds the string denoting the sword field in the database.
FieldSword = "sword"
// FieldCard holds the string denoting the card field in the database.
FieldCard = "card"
// FieldMode holds the string denoting the mode field in the database.
FieldMode = "mode"
// FieldToken holds the string denoting the token field in the database.
FieldToken = "token"
// FieldCp holds the string denoting the cp field in the database.
FieldCp = "cp"
// FieldCount holds the string denoting the count field in the database.
FieldCount = "count"
// FieldLocationX holds the string denoting the location_x field in the database.
FieldLocationX = "location_x"
// FieldLocationY holds the string denoting the location_y field in the database.
FieldLocationY = "location_y"
// FieldLocationZ holds the string denoting the location_z field in the database.
FieldLocationZ = "location_z"
// FieldLocationN holds the string denoting the location_n field in the database.
FieldLocationN = "location_n"
// FieldAuthor holds the string denoting the author field in the database.
FieldAuthor = "author"
// 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 ue in the database.
Table = "ues"
// OwnerTable is the table that holds the owner relation/edge.
OwnerTable = "ues"
// 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_ue"
)
// Columns holds all SQL columns for ue fields.
var Columns = []string{
FieldID,
FieldLimit,
FieldLimitBoss,
FieldLimitItem,
FieldPassword,
FieldLv,
FieldLvPoint,
FieldModel,
FieldSword,
FieldCard,
FieldMode,
FieldToken,
FieldCp,
FieldCount,
FieldLocationX,
FieldLocationY,
FieldLocationZ,
FieldLocationN,
FieldAuthor,
FieldCreatedAt,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "ues"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"user_ue",
}
// 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 (
// DefaultLimit holds the default value on creation for the "limit" field.
DefaultLimit bool
// DefaultLimitBoss holds the default value on creation for the "limit_boss" field.
DefaultLimitBoss bool
// DefaultLimitItem holds the default value on creation for the "limit_item" field.
DefaultLimitItem bool
// PasswordValidator is a validator for the "password" field. It is called by the builders before save.
PasswordValidator func(string) error
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
)
// OrderOption defines the ordering options for the Ue queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByLimit orders the results by the limit field.
func ByLimit(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLimit, opts...).ToFunc()
}
// ByLimitBoss orders the results by the limit_boss field.
func ByLimitBoss(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLimitBoss, opts...).ToFunc()
}
// ByLimitItem orders the results by the limit_item field.
func ByLimitItem(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLimitItem, opts...).ToFunc()
}
// ByPassword orders the results by the password field.
func ByPassword(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPassword, opts...).ToFunc()
}
// ByLv orders the results by the lv field.
func ByLv(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLv, opts...).ToFunc()
}
// ByLvPoint orders the results by the lv_point field.
func ByLvPoint(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLvPoint, opts...).ToFunc()
}
// ByModel orders the results by the model field.
func ByModel(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldModel, opts...).ToFunc()
}
// BySword orders the results by the sword field.
func BySword(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldSword, opts...).ToFunc()
}
// ByCard orders the results by the card field.
func ByCard(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCard, opts...).ToFunc()
}
// ByMode orders the results by the mode field.
func ByMode(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldMode, opts...).ToFunc()
}
// ByToken orders the results by the token field.
func ByToken(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldToken, opts...).ToFunc()
}
// ByCp orders the results by the cp field.
func ByCp(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCp, opts...).ToFunc()
}
// ByCount orders the results by the count field.
func ByCount(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCount, opts...).ToFunc()
}
// ByLocationX orders the results by the location_x field.
func ByLocationX(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLocationX, opts...).ToFunc()
}
// ByLocationY orders the results by the location_y field.
func ByLocationY(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLocationY, opts...).ToFunc()
}
// ByLocationZ orders the results by the location_z field.
func ByLocationZ(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLocationZ, opts...).ToFunc()
}
// ByLocationN orders the results by the location_n field.
func ByLocationN(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLocationN, opts...).ToFunc()
}
// ByAuthor orders the results by the author field.
func ByAuthor(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldAuthor, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByOwnerField orders the results by owner field.
func ByOwnerField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newOwnerStep(), sql.OrderByField(field, opts...))
}
}
func newOwnerStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(OwnerInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
)
}

1156
ent/ue/where.go Normal file

File diff suppressed because it is too large Load Diff

563
ent/ue_create.go Normal file
View File

@@ -0,0 +1,563 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"api/ent/ue"
"api/ent/user"
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UeCreate is the builder for creating a Ue entity.
type UeCreate struct {
config
mutation *UeMutation
hooks []Hook
}
// SetLimit sets the "limit" field.
func (uc *UeCreate) SetLimit(b bool) *UeCreate {
uc.mutation.SetLimit(b)
return uc
}
// SetNillableLimit sets the "limit" field if the given value is not nil.
func (uc *UeCreate) SetNillableLimit(b *bool) *UeCreate {
if b != nil {
uc.SetLimit(*b)
}
return uc
}
// SetLimitBoss sets the "limit_boss" field.
func (uc *UeCreate) SetLimitBoss(b bool) *UeCreate {
uc.mutation.SetLimitBoss(b)
return uc
}
// SetNillableLimitBoss sets the "limit_boss" field if the given value is not nil.
func (uc *UeCreate) SetNillableLimitBoss(b *bool) *UeCreate {
if b != nil {
uc.SetLimitBoss(*b)
}
return uc
}
// SetLimitItem sets the "limit_item" field.
func (uc *UeCreate) SetLimitItem(b bool) *UeCreate {
uc.mutation.SetLimitItem(b)
return uc
}
// SetNillableLimitItem sets the "limit_item" field if the given value is not nil.
func (uc *UeCreate) SetNillableLimitItem(b *bool) *UeCreate {
if b != nil {
uc.SetLimitItem(*b)
}
return uc
}
// SetPassword sets the "password" field.
func (uc *UeCreate) SetPassword(s string) *UeCreate {
uc.mutation.SetPassword(s)
return uc
}
// SetLv sets the "lv" field.
func (uc *UeCreate) SetLv(i int) *UeCreate {
uc.mutation.SetLv(i)
return uc
}
// SetNillableLv sets the "lv" field if the given value is not nil.
func (uc *UeCreate) SetNillableLv(i *int) *UeCreate {
if i != nil {
uc.SetLv(*i)
}
return uc
}
// SetLvPoint sets the "lv_point" field.
func (uc *UeCreate) SetLvPoint(i int) *UeCreate {
uc.mutation.SetLvPoint(i)
return uc
}
// SetNillableLvPoint sets the "lv_point" field if the given value is not nil.
func (uc *UeCreate) SetNillableLvPoint(i *int) *UeCreate {
if i != nil {
uc.SetLvPoint(*i)
}
return uc
}
// SetModel sets the "model" field.
func (uc *UeCreate) SetModel(i int) *UeCreate {
uc.mutation.SetModel(i)
return uc
}
// SetNillableModel sets the "model" field if the given value is not nil.
func (uc *UeCreate) SetNillableModel(i *int) *UeCreate {
if i != nil {
uc.SetModel(*i)
}
return uc
}
// SetSword sets the "sword" field.
func (uc *UeCreate) SetSword(i int) *UeCreate {
uc.mutation.SetSword(i)
return uc
}
// SetNillableSword sets the "sword" field if the given value is not nil.
func (uc *UeCreate) SetNillableSword(i *int) *UeCreate {
if i != nil {
uc.SetSword(*i)
}
return uc
}
// SetCard sets the "card" field.
func (uc *UeCreate) SetCard(i int) *UeCreate {
uc.mutation.SetCard(i)
return uc
}
// SetNillableCard sets the "card" field if the given value is not nil.
func (uc *UeCreate) SetNillableCard(i *int) *UeCreate {
if i != nil {
uc.SetCard(*i)
}
return uc
}
// SetMode sets the "mode" field.
func (uc *UeCreate) SetMode(s string) *UeCreate {
uc.mutation.SetMode(s)
return uc
}
// SetNillableMode sets the "mode" field if the given value is not nil.
func (uc *UeCreate) SetNillableMode(s *string) *UeCreate {
if s != nil {
uc.SetMode(*s)
}
return uc
}
// SetToken sets the "token" field.
func (uc *UeCreate) SetToken(s string) *UeCreate {
uc.mutation.SetToken(s)
return uc
}
// SetNillableToken sets the "token" field if the given value is not nil.
func (uc *UeCreate) SetNillableToken(s *string) *UeCreate {
if s != nil {
uc.SetToken(*s)
}
return uc
}
// SetCp sets the "cp" field.
func (uc *UeCreate) SetCp(i int) *UeCreate {
uc.mutation.SetCp(i)
return uc
}
// SetNillableCp sets the "cp" field if the given value is not nil.
func (uc *UeCreate) SetNillableCp(i *int) *UeCreate {
if i != nil {
uc.SetCp(*i)
}
return uc
}
// SetCount sets the "count" field.
func (uc *UeCreate) SetCount(i int) *UeCreate {
uc.mutation.SetCount(i)
return uc
}
// SetNillableCount sets the "count" field if the given value is not nil.
func (uc *UeCreate) SetNillableCount(i *int) *UeCreate {
if i != nil {
uc.SetCount(*i)
}
return uc
}
// SetLocationX sets the "location_x" field.
func (uc *UeCreate) SetLocationX(i int) *UeCreate {
uc.mutation.SetLocationX(i)
return uc
}
// SetNillableLocationX sets the "location_x" field if the given value is not nil.
func (uc *UeCreate) SetNillableLocationX(i *int) *UeCreate {
if i != nil {
uc.SetLocationX(*i)
}
return uc
}
// SetLocationY sets the "location_y" field.
func (uc *UeCreate) SetLocationY(i int) *UeCreate {
uc.mutation.SetLocationY(i)
return uc
}
// SetNillableLocationY sets the "location_y" field if the given value is not nil.
func (uc *UeCreate) SetNillableLocationY(i *int) *UeCreate {
if i != nil {
uc.SetLocationY(*i)
}
return uc
}
// SetLocationZ sets the "location_z" field.
func (uc *UeCreate) SetLocationZ(i int) *UeCreate {
uc.mutation.SetLocationZ(i)
return uc
}
// SetNillableLocationZ sets the "location_z" field if the given value is not nil.
func (uc *UeCreate) SetNillableLocationZ(i *int) *UeCreate {
if i != nil {
uc.SetLocationZ(*i)
}
return uc
}
// SetLocationN sets the "location_n" field.
func (uc *UeCreate) SetLocationN(i int) *UeCreate {
uc.mutation.SetLocationN(i)
return uc
}
// SetNillableLocationN sets the "location_n" field if the given value is not nil.
func (uc *UeCreate) SetNillableLocationN(i *int) *UeCreate {
if i != nil {
uc.SetLocationN(*i)
}
return uc
}
// SetAuthor sets the "author" field.
func (uc *UeCreate) SetAuthor(s string) *UeCreate {
uc.mutation.SetAuthor(s)
return uc
}
// SetNillableAuthor sets the "author" field if the given value is not nil.
func (uc *UeCreate) SetNillableAuthor(s *string) *UeCreate {
if s != nil {
uc.SetAuthor(*s)
}
return uc
}
// SetCreatedAt sets the "created_at" field.
func (uc *UeCreate) SetCreatedAt(t time.Time) *UeCreate {
uc.mutation.SetCreatedAt(t)
return uc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (uc *UeCreate) SetNillableCreatedAt(t *time.Time) *UeCreate {
if t != nil {
uc.SetCreatedAt(*t)
}
return uc
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (uc *UeCreate) SetOwnerID(id int) *UeCreate {
uc.mutation.SetOwnerID(id)
return uc
}
// SetOwner sets the "owner" edge to the User entity.
func (uc *UeCreate) SetOwner(u *User) *UeCreate {
return uc.SetOwnerID(u.ID)
}
// Mutation returns the UeMutation object of the builder.
func (uc *UeCreate) Mutation() *UeMutation {
return uc.mutation
}
// Save creates the Ue in the database.
func (uc *UeCreate) Save(ctx context.Context) (*Ue, error) {
uc.defaults()
return withHooks[*Ue, UeMutation](ctx, uc.sqlSave, uc.mutation, uc.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (uc *UeCreate) SaveX(ctx context.Context) *Ue {
v, err := uc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (uc *UeCreate) Exec(ctx context.Context) error {
_, err := uc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (uc *UeCreate) 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 *UeCreate) defaults() {
if _, ok := uc.mutation.Limit(); !ok {
v := ue.DefaultLimit
uc.mutation.SetLimit(v)
}
if _, ok := uc.mutation.LimitBoss(); !ok {
v := ue.DefaultLimitBoss
uc.mutation.SetLimitBoss(v)
}
if _, ok := uc.mutation.LimitItem(); !ok {
v := ue.DefaultLimitItem
uc.mutation.SetLimitItem(v)
}
if _, ok := uc.mutation.CreatedAt(); !ok {
v := ue.DefaultCreatedAt()
uc.mutation.SetCreatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (uc *UeCreate) check() error {
if _, ok := uc.mutation.Password(); !ok {
return &ValidationError{Name: "password", err: errors.New(`ent: missing required field "Ue.password"`)}
}
if v, ok := uc.mutation.Password(); ok {
if err := ue.PasswordValidator(v); err != nil {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "Ue.password": %w`, err)}
}
}
if _, ok := uc.mutation.OwnerID(); !ok {
return &ValidationError{Name: "owner", err: errors.New(`ent: missing required edge "Ue.owner"`)}
}
return nil
}
func (uc *UeCreate) sqlSave(ctx context.Context) (*Ue, 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 *UeCreate) createSpec() (*Ue, *sqlgraph.CreateSpec) {
var (
_node = &Ue{config: uc.config}
_spec = sqlgraph.NewCreateSpec(ue.Table, sqlgraph.NewFieldSpec(ue.FieldID, field.TypeInt))
)
if value, ok := uc.mutation.Limit(); ok {
_spec.SetField(ue.FieldLimit, field.TypeBool, value)
_node.Limit = value
}
if value, ok := uc.mutation.LimitBoss(); ok {
_spec.SetField(ue.FieldLimitBoss, field.TypeBool, value)
_node.LimitBoss = value
}
if value, ok := uc.mutation.LimitItem(); ok {
_spec.SetField(ue.FieldLimitItem, field.TypeBool, value)
_node.LimitItem = value
}
if value, ok := uc.mutation.Password(); ok {
_spec.SetField(ue.FieldPassword, field.TypeString, value)
_node.Password = value
}
if value, ok := uc.mutation.Lv(); ok {
_spec.SetField(ue.FieldLv, field.TypeInt, value)
_node.Lv = value
}
if value, ok := uc.mutation.LvPoint(); ok {
_spec.SetField(ue.FieldLvPoint, field.TypeInt, value)
_node.LvPoint = value
}
if value, ok := uc.mutation.Model(); ok {
_spec.SetField(ue.FieldModel, field.TypeInt, value)
_node.Model = value
}
if value, ok := uc.mutation.Sword(); ok {
_spec.SetField(ue.FieldSword, field.TypeInt, value)
_node.Sword = value
}
if value, ok := uc.mutation.Card(); ok {
_spec.SetField(ue.FieldCard, field.TypeInt, value)
_node.Card = value
}
if value, ok := uc.mutation.Mode(); ok {
_spec.SetField(ue.FieldMode, field.TypeString, value)
_node.Mode = value
}
if value, ok := uc.mutation.Token(); ok {
_spec.SetField(ue.FieldToken, field.TypeString, value)
_node.Token = value
}
if value, ok := uc.mutation.Cp(); ok {
_spec.SetField(ue.FieldCp, field.TypeInt, value)
_node.Cp = value
}
if value, ok := uc.mutation.Count(); ok {
_spec.SetField(ue.FieldCount, field.TypeInt, value)
_node.Count = value
}
if value, ok := uc.mutation.LocationX(); ok {
_spec.SetField(ue.FieldLocationX, field.TypeInt, value)
_node.LocationX = value
}
if value, ok := uc.mutation.LocationY(); ok {
_spec.SetField(ue.FieldLocationY, field.TypeInt, value)
_node.LocationY = value
}
if value, ok := uc.mutation.LocationZ(); ok {
_spec.SetField(ue.FieldLocationZ, field.TypeInt, value)
_node.LocationZ = value
}
if value, ok := uc.mutation.LocationN(); ok {
_spec.SetField(ue.FieldLocationN, field.TypeInt, value)
_node.LocationN = value
}
if value, ok := uc.mutation.Author(); ok {
_spec.SetField(ue.FieldAuthor, field.TypeString, value)
_node.Author = value
}
if value, ok := uc.mutation.CreatedAt(); ok {
_spec.SetField(ue.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
if nodes := uc.mutation.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: ue.OwnerTable,
Columns: []string{ue.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.user_ue = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// UeCreateBulk is the builder for creating many Ue entities in bulk.
type UeCreateBulk struct {
config
builders []*UeCreate
}
// Save creates the Ue entities in the database.
func (ucb *UeCreateBulk) Save(ctx context.Context) ([]*Ue, error) {
specs := make([]*sqlgraph.CreateSpec, len(ucb.builders))
nodes := make([]*Ue, 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.(*UeMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, 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 *UeCreateBulk) SaveX(ctx context.Context) []*Ue {
v, err := ucb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (ucb *UeCreateBulk) Exec(ctx context.Context) error {
_, err := ucb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ucb *UeCreateBulk) ExecX(ctx context.Context) {
if err := ucb.Exec(ctx); err != nil {
panic(err)
}
}

88
ent/ue_delete.go Normal file
View File

@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"api/ent/predicate"
"api/ent/ue"
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UeDelete is the builder for deleting a Ue entity.
type UeDelete struct {
config
hooks []Hook
mutation *UeMutation
}
// Where appends a list predicates to the UeDelete builder.
func (ud *UeDelete) Where(ps ...predicate.Ue) *UeDelete {
ud.mutation.Where(ps...)
return ud
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (ud *UeDelete) Exec(ctx context.Context) (int, error) {
return withHooks[int, UeMutation](ctx, ud.sqlExec, ud.mutation, ud.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (ud *UeDelete) ExecX(ctx context.Context) int {
n, err := ud.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (ud *UeDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(ue.Table, sqlgraph.NewFieldSpec(ue.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
}
// UeDeleteOne is the builder for deleting a single Ue entity.
type UeDeleteOne struct {
ud *UeDelete
}
// Where appends a list predicates to the UeDelete builder.
func (udo *UeDeleteOne) Where(ps ...predicate.Ue) *UeDeleteOne {
udo.ud.mutation.Where(ps...)
return udo
}
// Exec executes the deletion query.
func (udo *UeDeleteOne) Exec(ctx context.Context) error {
n, err := udo.ud.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{ue.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (udo *UeDeleteOne) ExecX(ctx context.Context) {
if err := udo.Exec(ctx); err != nil {
panic(err)
}
}

613
ent/ue_query.go Normal file
View File

@@ -0,0 +1,613 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"api/ent/predicate"
"api/ent/ue"
"api/ent/user"
"context"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UeQuery is the builder for querying Ue entities.
type UeQuery struct {
config
ctx *QueryContext
order []ue.OrderOption
inters []Interceptor
predicates []predicate.Ue
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 UeQuery builder.
func (uq *UeQuery) Where(ps ...predicate.Ue) *UeQuery {
uq.predicates = append(uq.predicates, ps...)
return uq
}
// Limit the number of records to be returned by this query.
func (uq *UeQuery) Limit(limit int) *UeQuery {
uq.ctx.Limit = &limit
return uq
}
// Offset to start from.
func (uq *UeQuery) Offset(offset int) *UeQuery {
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 *UeQuery) Unique(unique bool) *UeQuery {
uq.ctx.Unique = &unique
return uq
}
// Order specifies how the records should be ordered.
func (uq *UeQuery) Order(o ...ue.OrderOption) *UeQuery {
uq.order = append(uq.order, o...)
return uq
}
// QueryOwner chains the current query on the "owner" edge.
func (uq *UeQuery) QueryOwner() *UserQuery {
query := (&UserClient{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(ue.Table, ue.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, ue.OwnerTable, ue.OwnerColumn),
)
fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Ue entity from the query.
// Returns a *NotFoundError when no Ue was found.
func (uq *UeQuery) First(ctx context.Context) (*Ue, 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{ue.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (uq *UeQuery) FirstX(ctx context.Context) *Ue {
node, err := uq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Ue ID from the query.
// Returns a *NotFoundError when no Ue ID was found.
func (uq *UeQuery) 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{ue.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (uq *UeQuery) FirstIDX(ctx context.Context) int {
id, err := uq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Ue entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Ue entity is found.
// Returns a *NotFoundError when no Ue entities are found.
func (uq *UeQuery) Only(ctx context.Context) (*Ue, 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{ue.Label}
default:
return nil, &NotSingularError{ue.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (uq *UeQuery) OnlyX(ctx context.Context) *Ue {
node, err := uq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Ue ID in the query.
// Returns a *NotSingularError when more than one Ue ID is found.
// Returns a *NotFoundError when no entities are found.
func (uq *UeQuery) 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{ue.Label}
default:
err = &NotSingularError{ue.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (uq *UeQuery) 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 Ues.
func (uq *UeQuery) All(ctx context.Context) ([]*Ue, error) {
ctx = setContextOp(ctx, uq.ctx, "All")
if err := uq.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Ue, *UeQuery]()
return withInterceptors[[]*Ue](ctx, uq, qr, uq.inters)
}
// AllX is like All, but panics if an error occurs.
func (uq *UeQuery) AllX(ctx context.Context) []*Ue {
nodes, err := uq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Ue IDs.
func (uq *UeQuery) 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(ue.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (uq *UeQuery) 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 *UeQuery) 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[*UeQuery](), uq.inters)
}
// CountX is like Count, but panics if an error occurs.
func (uq *UeQuery) 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 *UeQuery) 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 *UeQuery) ExistX(ctx context.Context) bool {
exist, err := uq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the UeQuery 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 *UeQuery) Clone() *UeQuery {
if uq == nil {
return nil
}
return &UeQuery{
config: uq.config,
ctx: uq.ctx.Clone(),
order: append([]ue.OrderOption{}, uq.order...),
inters: append([]Interceptor{}, uq.inters...),
predicates: append([]predicate.Ue{}, uq.predicates...),
withOwner: uq.withOwner.Clone(),
// clone intermediate query.
sql: uq.sql.Clone(),
path: uq.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 (uq *UeQuery) WithOwner(opts ...func(*UserQuery)) *UeQuery {
query := (&UserClient{config: uq.config}).Query()
for _, opt := range opts {
opt(query)
}
uq.withOwner = 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 {
// Limit bool `json:"limit,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Ue.Query().
// GroupBy(ue.FieldLimit).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (uq *UeQuery) GroupBy(field string, fields ...string) *UeGroupBy {
uq.ctx.Fields = append([]string{field}, fields...)
grbuild := &UeGroupBy{build: uq}
grbuild.flds = &uq.ctx.Fields
grbuild.label = ue.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 {
// Limit bool `json:"limit,omitempty"`
// }
//
// client.Ue.Query().
// Select(ue.FieldLimit).
// Scan(ctx, &v)
func (uq *UeQuery) Select(fields ...string) *UeSelect {
uq.ctx.Fields = append(uq.ctx.Fields, fields...)
sbuild := &UeSelect{UeQuery: uq}
sbuild.label = ue.Label
sbuild.flds, sbuild.scan = &uq.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a UeSelect configured with the given aggregations.
func (uq *UeQuery) Aggregate(fns ...AggregateFunc) *UeSelect {
return uq.Select().Aggregate(fns...)
}
func (uq *UeQuery) 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 !ue.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 *UeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Ue, error) {
var (
nodes = []*Ue{}
withFKs = uq.withFKs
_spec = uq.querySpec()
loadedTypes = [1]bool{
uq.withOwner != nil,
}
)
if uq.withOwner != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, ue.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Ue).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Ue{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.withOwner; query != nil {
if err := uq.loadOwner(ctx, query, nodes, nil,
func(n *Ue, e *User) { n.Edges.Owner = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (uq *UeQuery) loadOwner(ctx context.Context, query *UserQuery, nodes []*Ue, init func(*Ue), assign func(*Ue, *User)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*Ue)
for i := range nodes {
if nodes[i].user_ue == nil {
continue
}
fk := *nodes[i].user_ue
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_ue" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (uq *UeQuery) 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 *UeQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(ue.Table, ue.Columns, sqlgraph.NewFieldSpec(ue.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, ue.FieldID)
for i := range fields {
if fields[i] != ue.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 *UeQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(uq.driver.Dialect())
t1 := builder.Table(ue.Table)
columns := uq.ctx.Fields
if len(columns) == 0 {
columns = ue.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
}
// UeGroupBy is the group-by builder for Ue entities.
type UeGroupBy struct {
selector
build *UeQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (ugb *UeGroupBy) Aggregate(fns ...AggregateFunc) *UeGroupBy {
ugb.fns = append(ugb.fns, fns...)
return ugb
}
// Scan applies the selector query and scans the result into the given value.
func (ugb *UeGroupBy) 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[*UeQuery, *UeGroupBy](ctx, ugb.build, ugb, ugb.build.inters, v)
}
func (ugb *UeGroupBy) sqlScan(ctx context.Context, root *UeQuery, 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)
}
// UeSelect is the builder for selecting fields of Ue entities.
type UeSelect struct {
*UeQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (us *UeSelect) Aggregate(fns ...AggregateFunc) *UeSelect {
us.fns = append(us.fns, fns...)
return us
}
// Scan applies the selector query and scans the result into the given value.
func (us *UeSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, us.ctx, "Select")
if err := us.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*UeQuery, *UeSelect](ctx, us.UeQuery, us, us.inters, v)
}
func (us *UeSelect) sqlScan(ctx context.Context, root *UeQuery, 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)
}

1400
ent/ue_update.go Normal file

File diff suppressed because it is too large Load Diff

664
ent/user.go Normal file
View File

@@ -0,0 +1,664 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"api/ent/user"
"fmt"
"strings"
"time"
"entgo.io/ent"
"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"`
// Did holds the value of the "did" field.
Did string `json:"did,omitempty"`
// Member holds the value of the "member" field.
Member bool `json:"member,omitempty"`
// Book holds the value of the "book" field.
Book bool `json:"book,omitempty"`
// Manga holds the value of the "manga" field.
Manga bool `json:"manga,omitempty"`
// Badge holds the value of the "badge" field.
Badge bool `json:"badge,omitempty"`
// Bsky holds the value of the "bsky" field.
Bsky bool `json:"bsky,omitempty"`
// Mastodon holds the value of the "mastodon" field.
Mastodon bool `json:"mastodon,omitempty"`
// Delete holds the value of the "delete" field.
Delete bool `json:"delete,omitempty"`
// Handle holds the value of the "handle" field.
Handle bool `json:"handle,omitempty"`
// Token holds the value of the "token" field.
Token string `json:"-"`
// Password holds the value of the "password" field.
Password string `json:"-"`
// 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"`
// RaidAt holds the value of the "raid_at" field.
RaidAt time.Time `json:"raid_at,omitempty"`
// ServerAt holds the value of the "server_at" field.
ServerAt time.Time `json:"server_at,omitempty"`
// EggAt holds the value of the "egg_at" field.
EggAt time.Time `json:"egg_at,omitempty"`
// Luck holds the value of the "luck" field.
Luck int `json:"luck,omitempty"`
// LuckAt holds the value of the "luck_at" field.
LuckAt time.Time `json:"luck_at,omitempty"`
// Like holds the value of the "like" field.
Like int `json:"like,omitempty"`
// LikeRank holds the value of the "like_rank" field.
LikeRank int `json:"like_rank,omitempty"`
// LikeAt holds the value of the "like_at" field.
LikeAt time.Time `json:"like_at,omitempty"`
// Fav holds the value of the "fav" field.
Fav int `json:"fav,omitempty"`
// Ten holds the value of the "ten" field.
Ten bool `json:"ten,omitempty"`
// TenSu holds the value of the "ten_su" field.
TenSu int `json:"ten_su,omitempty"`
// TenKai holds the value of the "ten_kai" field.
TenKai int `json:"ten_kai,omitempty"`
// Aiten holds the value of the "aiten" field.
Aiten int `json:"aiten,omitempty"`
// TenCard holds the value of the "ten_card" field.
TenCard string `json:"ten_card,omitempty"`
// TenDelete holds the value of the "ten_delete" field.
TenDelete string `json:"ten_delete,omitempty"`
// TenPost holds the value of the "ten_post" field.
TenPost string `json:"ten_post,omitempty"`
// TenGet holds the value of the "ten_get" field.
TenGet string `json:"ten_get,omitempty"`
// TenAt holds the value of the "ten_at" field.
TenAt time.Time `json:"ten_at,omitempty"`
// Next holds the value of the "next" field.
Next string `json:"next,omitempty"`
// Room holds the value of the "room" field.
Room int `json:"room,omitempty"`
// Model holds the value of the "model" field.
Model bool `json:"model,omitempty"`
// ModelAt holds the value of the "model_at" field.
ModelAt time.Time `json:"model_at,omitempty"`
// ModelAttack holds the value of the "model_attack" field.
ModelAttack int `json:"model_attack,omitempty"`
// ModelLimit holds the value of the "model_limit" field.
ModelLimit int `json:"model_limit,omitempty"`
// ModelSkill holds the value of the "model_skill" field.
ModelSkill int `json:"model_skill,omitempty"`
// ModelMode holds the value of the "model_mode" field.
ModelMode int `json:"model_mode,omitempty"`
// ModelCritical holds the value of the "model_critical" field.
ModelCritical int `json:"model_critical,omitempty"`
// ModelCriticalD holds the value of the "model_critical_d" field.
ModelCriticalD int `json:"model_critical_d,omitempty"`
// Game holds the value of the "game" field.
Game bool `json:"game,omitempty"`
// GameTest holds the value of the "game_test" field.
GameTest bool `json:"game_test,omitempty"`
// GameEnd holds the value of the "game_end" field.
GameEnd bool `json:"game_end,omitempty"`
// GameAccount holds the value of the "game_account" field.
GameAccount bool `json:"game_account,omitempty"`
// GameLv holds the value of the "game_lv" field.
GameLv int `json:"game_lv,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
selectValues sql.SelectValues
}
// 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"`
// Ue holds the value of the ue edge.
Ue []*Ue `json:"ue,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]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"}
}
// UeOrErr returns the Ue value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) UeOrErr() ([]*Ue, error) {
if e.loadedTypes[1] {
return e.Ue, nil
}
return nil, &NotLoadedError{edge: "ue"}
}
// 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.FieldMember, user.FieldBook, user.FieldManga, user.FieldBadge, user.FieldBsky, user.FieldMastodon, user.FieldDelete, user.FieldHandle, user.FieldTen, user.FieldModel, user.FieldGame, user.FieldGameTest, user.FieldGameEnd, user.FieldGameAccount:
values[i] = new(sql.NullBool)
case user.FieldID, user.FieldLuck, user.FieldLike, user.FieldLikeRank, user.FieldFav, user.FieldTenSu, user.FieldTenKai, user.FieldAiten, user.FieldRoom, user.FieldModelAttack, user.FieldModelLimit, user.FieldModelSkill, user.FieldModelMode, user.FieldModelCritical, user.FieldModelCriticalD, user.FieldGameLv:
values[i] = new(sql.NullInt64)
case user.FieldUsername, user.FieldDid, user.FieldToken, user.FieldPassword, user.FieldTenCard, user.FieldTenDelete, user.FieldTenPost, user.FieldTenGet, user.FieldNext:
values[i] = new(sql.NullString)
case user.FieldCreatedAt, user.FieldUpdatedAt, user.FieldRaidAt, user.FieldServerAt, user.FieldEggAt, user.FieldLuckAt, user.FieldLikeAt, user.FieldTenAt, user.FieldModelAt:
values[i] = new(sql.NullTime)
case user.ForeignKeys[0]: // group_users
values[i] = new(sql.NullInt64)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the 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.FieldDid:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field did", values[i])
} else if value.Valid {
u.Did = value.String
}
case user.FieldMember:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field member", values[i])
} else if value.Valid {
u.Member = value.Bool
}
case user.FieldBook:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field book", values[i])
} else if value.Valid {
u.Book = value.Bool
}
case user.FieldManga:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field manga", values[i])
} else if value.Valid {
u.Manga = value.Bool
}
case user.FieldBadge:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field badge", values[i])
} else if value.Valid {
u.Badge = value.Bool
}
case user.FieldBsky:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field bsky", values[i])
} else if value.Valid {
u.Bsky = value.Bool
}
case user.FieldMastodon:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field mastodon", values[i])
} else if value.Valid {
u.Mastodon = value.Bool
}
case user.FieldDelete:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field delete", values[i])
} else if value.Valid {
u.Delete = value.Bool
}
case user.FieldHandle:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field handle", values[i])
} else if value.Valid {
u.Handle = value.Bool
}
case user.FieldToken:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field token", values[i])
} else if value.Valid {
u.Token = value.String
}
case user.FieldPassword:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field password", values[i])
} else if value.Valid {
u.Password = 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.FieldRaidAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field raid_at", values[i])
} else if value.Valid {
u.RaidAt = value.Time
}
case user.FieldServerAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field server_at", values[i])
} else if value.Valid {
u.ServerAt = value.Time
}
case user.FieldEggAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field egg_at", values[i])
} else if value.Valid {
u.EggAt = value.Time
}
case user.FieldLuck:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field luck", values[i])
} else if value.Valid {
u.Luck = int(value.Int64)
}
case user.FieldLuckAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field luck_at", values[i])
} else if value.Valid {
u.LuckAt = value.Time
}
case user.FieldLike:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field like", values[i])
} else if value.Valid {
u.Like = int(value.Int64)
}
case user.FieldLikeRank:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field like_rank", values[i])
} else if value.Valid {
u.LikeRank = int(value.Int64)
}
case user.FieldLikeAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field like_at", values[i])
} else if value.Valid {
u.LikeAt = value.Time
}
case user.FieldFav:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field fav", values[i])
} else if value.Valid {
u.Fav = int(value.Int64)
}
case user.FieldTen:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field ten", values[i])
} else if value.Valid {
u.Ten = value.Bool
}
case user.FieldTenSu:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field ten_su", values[i])
} else if value.Valid {
u.TenSu = int(value.Int64)
}
case user.FieldTenKai:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field ten_kai", values[i])
} else if value.Valid {
u.TenKai = int(value.Int64)
}
case user.FieldAiten:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field aiten", values[i])
} else if value.Valid {
u.Aiten = int(value.Int64)
}
case user.FieldTenCard:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field ten_card", values[i])
} else if value.Valid {
u.TenCard = value.String
}
case user.FieldTenDelete:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field ten_delete", values[i])
} else if value.Valid {
u.TenDelete = value.String
}
case user.FieldTenPost:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field ten_post", values[i])
} else if value.Valid {
u.TenPost = value.String
}
case user.FieldTenGet:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field ten_get", values[i])
} else if value.Valid {
u.TenGet = value.String
}
case user.FieldTenAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field ten_at", values[i])
} else if value.Valid {
u.TenAt = 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.FieldRoom:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field room", values[i])
} else if value.Valid {
u.Room = int(value.Int64)
}
case user.FieldModel:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field model", values[i])
} else if value.Valid {
u.Model = value.Bool
}
case user.FieldModelAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field model_at", values[i])
} else if value.Valid {
u.ModelAt = value.Time
}
case user.FieldModelAttack:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field model_attack", values[i])
} else if value.Valid {
u.ModelAttack = int(value.Int64)
}
case user.FieldModelLimit:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field model_limit", values[i])
} else if value.Valid {
u.ModelLimit = int(value.Int64)
}
case user.FieldModelSkill:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field model_skill", values[i])
} else if value.Valid {
u.ModelSkill = int(value.Int64)
}
case user.FieldModelMode:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field model_mode", values[i])
} else if value.Valid {
u.ModelMode = int(value.Int64)
}
case user.FieldModelCritical:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field model_critical", values[i])
} else if value.Valid {
u.ModelCritical = int(value.Int64)
}
case user.FieldModelCriticalD:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field model_critical_d", values[i])
} else if value.Valid {
u.ModelCriticalD = int(value.Int64)
}
case user.FieldGame:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field game", values[i])
} else if value.Valid {
u.Game = value.Bool
}
case user.FieldGameTest:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field game_test", values[i])
} else if value.Valid {
u.GameTest = value.Bool
}
case user.FieldGameEnd:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field game_end", values[i])
} else if value.Valid {
u.GameEnd = value.Bool
}
case user.FieldGameAccount:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field game_account", values[i])
} else if value.Valid {
u.GameAccount = value.Bool
}
case user.FieldGameLv:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field game_lv", values[i])
} else if value.Valid {
u.GameLv = int(value.Int64)
}
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)
}
default:
u.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the User.
// This includes values selected through modifiers, order, etc.
func (u *User) Value(name string) (ent.Value, error) {
return u.selectValues.Get(name)
}
// QueryCard queries the "card" edge of the User entity.
func (u *User) QueryCard() *CardQuery {
return NewUserClient(u.config).QueryCard(u)
}
// QueryUe queries the "ue" edge of the User entity.
func (u *User) QueryUe() *UeQuery {
return NewUserClient(u.config).QueryUe(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("did=")
builder.WriteString(u.Did)
builder.WriteString(", ")
builder.WriteString("member=")
builder.WriteString(fmt.Sprintf("%v", u.Member))
builder.WriteString(", ")
builder.WriteString("book=")
builder.WriteString(fmt.Sprintf("%v", u.Book))
builder.WriteString(", ")
builder.WriteString("manga=")
builder.WriteString(fmt.Sprintf("%v", u.Manga))
builder.WriteString(", ")
builder.WriteString("badge=")
builder.WriteString(fmt.Sprintf("%v", u.Badge))
builder.WriteString(", ")
builder.WriteString("bsky=")
builder.WriteString(fmt.Sprintf("%v", u.Bsky))
builder.WriteString(", ")
builder.WriteString("mastodon=")
builder.WriteString(fmt.Sprintf("%v", u.Mastodon))
builder.WriteString(", ")
builder.WriteString("delete=")
builder.WriteString(fmt.Sprintf("%v", u.Delete))
builder.WriteString(", ")
builder.WriteString("handle=")
builder.WriteString(fmt.Sprintf("%v", u.Handle))
builder.WriteString(", ")
builder.WriteString("token=<sensitive>")
builder.WriteString(", ")
builder.WriteString("password=<sensitive>")
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("raid_at=")
builder.WriteString(u.RaidAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("server_at=")
builder.WriteString(u.ServerAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("egg_at=")
builder.WriteString(u.EggAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("luck=")
builder.WriteString(fmt.Sprintf("%v", u.Luck))
builder.WriteString(", ")
builder.WriteString("luck_at=")
builder.WriteString(u.LuckAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("like=")
builder.WriteString(fmt.Sprintf("%v", u.Like))
builder.WriteString(", ")
builder.WriteString("like_rank=")
builder.WriteString(fmt.Sprintf("%v", u.LikeRank))
builder.WriteString(", ")
builder.WriteString("like_at=")
builder.WriteString(u.LikeAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("fav=")
builder.WriteString(fmt.Sprintf("%v", u.Fav))
builder.WriteString(", ")
builder.WriteString("ten=")
builder.WriteString(fmt.Sprintf("%v", u.Ten))
builder.WriteString(", ")
builder.WriteString("ten_su=")
builder.WriteString(fmt.Sprintf("%v", u.TenSu))
builder.WriteString(", ")
builder.WriteString("ten_kai=")
builder.WriteString(fmt.Sprintf("%v", u.TenKai))
builder.WriteString(", ")
builder.WriteString("aiten=")
builder.WriteString(fmt.Sprintf("%v", u.Aiten))
builder.WriteString(", ")
builder.WriteString("ten_card=")
builder.WriteString(u.TenCard)
builder.WriteString(", ")
builder.WriteString("ten_delete=")
builder.WriteString(u.TenDelete)
builder.WriteString(", ")
builder.WriteString("ten_post=")
builder.WriteString(u.TenPost)
builder.WriteString(", ")
builder.WriteString("ten_get=")
builder.WriteString(u.TenGet)
builder.WriteString(", ")
builder.WriteString("ten_at=")
builder.WriteString(u.TenAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("next=")
builder.WriteString(u.Next)
builder.WriteString(", ")
builder.WriteString("room=")
builder.WriteString(fmt.Sprintf("%v", u.Room))
builder.WriteString(", ")
builder.WriteString("model=")
builder.WriteString(fmt.Sprintf("%v", u.Model))
builder.WriteString(", ")
builder.WriteString("model_at=")
builder.WriteString(u.ModelAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("model_attack=")
builder.WriteString(fmt.Sprintf("%v", u.ModelAttack))
builder.WriteString(", ")
builder.WriteString("model_limit=")
builder.WriteString(fmt.Sprintf("%v", u.ModelLimit))
builder.WriteString(", ")
builder.WriteString("model_skill=")
builder.WriteString(fmt.Sprintf("%v", u.ModelSkill))
builder.WriteString(", ")
builder.WriteString("model_mode=")
builder.WriteString(fmt.Sprintf("%v", u.ModelMode))
builder.WriteString(", ")
builder.WriteString("model_critical=")
builder.WriteString(fmt.Sprintf("%v", u.ModelCritical))
builder.WriteString(", ")
builder.WriteString("model_critical_d=")
builder.WriteString(fmt.Sprintf("%v", u.ModelCriticalD))
builder.WriteString(", ")
builder.WriteString("game=")
builder.WriteString(fmt.Sprintf("%v", u.Game))
builder.WriteString(", ")
builder.WriteString("game_test=")
builder.WriteString(fmt.Sprintf("%v", u.GameTest))
builder.WriteString(", ")
builder.WriteString("game_end=")
builder.WriteString(fmt.Sprintf("%v", u.GameEnd))
builder.WriteString(", ")
builder.WriteString("game_account=")
builder.WriteString(fmt.Sprintf("%v", u.GameAccount))
builder.WriteString(", ")
builder.WriteString("game_lv=")
builder.WriteString(fmt.Sprintf("%v", u.GameLv))
builder.WriteByte(')')
return builder.String()
}
// Users is a parsable slice of User.
type Users []*User

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

@@ -0,0 +1,540 @@
// Code generated by ent, DO NOT EDIT.
package user
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
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"
// FieldDid holds the string denoting the did field in the database.
FieldDid = "did"
// FieldMember holds the string denoting the member field in the database.
FieldMember = "member"
// FieldBook holds the string denoting the book field in the database.
FieldBook = "book"
// FieldManga holds the string denoting the manga field in the database.
FieldManga = "manga"
// FieldBadge holds the string denoting the badge field in the database.
FieldBadge = "badge"
// FieldBsky holds the string denoting the bsky field in the database.
FieldBsky = "bsky"
// FieldMastodon holds the string denoting the mastodon field in the database.
FieldMastodon = "mastodon"
// FieldDelete holds the string denoting the delete field in the database.
FieldDelete = "delete"
// FieldHandle holds the string denoting the handle field in the database.
FieldHandle = "handle"
// FieldToken holds the string denoting the token field in the database.
FieldToken = "token"
// FieldPassword holds the string denoting the password field in the database.
FieldPassword = "password"
// 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"
// FieldRaidAt holds the string denoting the raid_at field in the database.
FieldRaidAt = "raid_at"
// FieldServerAt holds the string denoting the server_at field in the database.
FieldServerAt = "server_at"
// FieldEggAt holds the string denoting the egg_at field in the database.
FieldEggAt = "egg_at"
// FieldLuck holds the string denoting the luck field in the database.
FieldLuck = "luck"
// FieldLuckAt holds the string denoting the luck_at field in the database.
FieldLuckAt = "luck_at"
// FieldLike holds the string denoting the like field in the database.
FieldLike = "like"
// FieldLikeRank holds the string denoting the like_rank field in the database.
FieldLikeRank = "like_rank"
// FieldLikeAt holds the string denoting the like_at field in the database.
FieldLikeAt = "like_at"
// FieldFav holds the string denoting the fav field in the database.
FieldFav = "fav"
// FieldTen holds the string denoting the ten field in the database.
FieldTen = "ten"
// FieldTenSu holds the string denoting the ten_su field in the database.
FieldTenSu = "ten_su"
// FieldTenKai holds the string denoting the ten_kai field in the database.
FieldTenKai = "ten_kai"
// FieldAiten holds the string denoting the aiten field in the database.
FieldAiten = "aiten"
// FieldTenCard holds the string denoting the ten_card field in the database.
FieldTenCard = "ten_card"
// FieldTenDelete holds the string denoting the ten_delete field in the database.
FieldTenDelete = "ten_delete"
// FieldTenPost holds the string denoting the ten_post field in the database.
FieldTenPost = "ten_post"
// FieldTenGet holds the string denoting the ten_get field in the database.
FieldTenGet = "ten_get"
// FieldTenAt holds the string denoting the ten_at field in the database.
FieldTenAt = "ten_at"
// FieldNext holds the string denoting the next field in the database.
FieldNext = "next"
// FieldRoom holds the string denoting the room field in the database.
FieldRoom = "room"
// FieldModel holds the string denoting the model field in the database.
FieldModel = "model"
// FieldModelAt holds the string denoting the model_at field in the database.
FieldModelAt = "model_at"
// FieldModelAttack holds the string denoting the model_attack field in the database.
FieldModelAttack = "model_attack"
// FieldModelLimit holds the string denoting the model_limit field in the database.
FieldModelLimit = "model_limit"
// FieldModelSkill holds the string denoting the model_skill field in the database.
FieldModelSkill = "model_skill"
// FieldModelMode holds the string denoting the model_mode field in the database.
FieldModelMode = "model_mode"
// FieldModelCritical holds the string denoting the model_critical field in the database.
FieldModelCritical = "model_critical"
// FieldModelCriticalD holds the string denoting the model_critical_d field in the database.
FieldModelCriticalD = "model_critical_d"
// FieldGame holds the string denoting the game field in the database.
FieldGame = "game"
// FieldGameTest holds the string denoting the game_test field in the database.
FieldGameTest = "game_test"
// FieldGameEnd holds the string denoting the game_end field in the database.
FieldGameEnd = "game_end"
// FieldGameAccount holds the string denoting the game_account field in the database.
FieldGameAccount = "game_account"
// FieldGameLv holds the string denoting the game_lv field in the database.
FieldGameLv = "game_lv"
// EdgeCard holds the string denoting the card edge name in mutations.
EdgeCard = "card"
// EdgeUe holds the string denoting the ue edge name in mutations.
EdgeUe = "ue"
// 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"
// UeTable is the table that holds the ue relation/edge.
UeTable = "ues"
// UeInverseTable is the table name for the Ue entity.
// It exists in this package in order to avoid circular dependency with the "ue" package.
UeInverseTable = "ues"
// UeColumn is the table column denoting the ue relation/edge.
UeColumn = "user_ue"
)
// Columns holds all SQL columns for user fields.
var Columns = []string{
FieldID,
FieldUsername,
FieldDid,
FieldMember,
FieldBook,
FieldManga,
FieldBadge,
FieldBsky,
FieldMastodon,
FieldDelete,
FieldHandle,
FieldToken,
FieldPassword,
FieldCreatedAt,
FieldUpdatedAt,
FieldRaidAt,
FieldServerAt,
FieldEggAt,
FieldLuck,
FieldLuckAt,
FieldLike,
FieldLikeRank,
FieldLikeAt,
FieldFav,
FieldTen,
FieldTenSu,
FieldTenKai,
FieldAiten,
FieldTenCard,
FieldTenDelete,
FieldTenPost,
FieldTenGet,
FieldTenAt,
FieldNext,
FieldRoom,
FieldModel,
FieldModelAt,
FieldModelAttack,
FieldModelLimit,
FieldModelSkill,
FieldModelMode,
FieldModelCritical,
FieldModelCriticalD,
FieldGame,
FieldGameTest,
FieldGameEnd,
FieldGameAccount,
FieldGameLv,
}
// 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
// DefaultMember holds the default value on creation for the "member" field.
DefaultMember bool
// DefaultBook holds the default value on creation for the "book" field.
DefaultBook bool
// DefaultManga holds the default value on creation for the "manga" field.
DefaultManga bool
// DefaultBadge holds the default value on creation for the "badge" field.
DefaultBadge bool
// DefaultBsky holds the default value on creation for the "bsky" field.
DefaultBsky bool
// DefaultMastodon holds the default value on creation for the "mastodon" field.
DefaultMastodon bool
// DefaultDelete holds the default value on creation for the "delete" field.
DefaultDelete bool
// DefaultHandle holds the default value on creation for the "handle" field.
DefaultHandle bool
// PasswordValidator is a validator for the "password" field. It is called by the builders before save.
PasswordValidator 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
// DefaultRaidAt holds the default value on creation for the "raid_at" field.
DefaultRaidAt func() time.Time
// DefaultServerAt holds the default value on creation for the "server_at" field.
DefaultServerAt func() time.Time
// DefaultEggAt holds the default value on creation for the "egg_at" field.
DefaultEggAt func() time.Time
// DefaultLuckAt holds the default value on creation for the "luck_at" field.
DefaultLuckAt func() time.Time
// DefaultLikeAt holds the default value on creation for the "like_at" field.
DefaultLikeAt func() time.Time
// DefaultTenAt holds the default value on creation for the "ten_at" field.
DefaultTenAt func() time.Time
// DefaultNext holds the default value on creation for the "next" field.
DefaultNext string
// DefaultModelAt holds the default value on creation for the "model_at" field.
DefaultModelAt func() time.Time
// DefaultGame holds the default value on creation for the "game" field.
DefaultGame bool
// DefaultGameTest holds the default value on creation for the "game_test" field.
DefaultGameTest bool
// DefaultGameEnd holds the default value on creation for the "game_end" field.
DefaultGameEnd bool
// DefaultGameAccount holds the default value on creation for the "game_account" field.
DefaultGameAccount bool
)
// OrderOption defines the ordering options for the User queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByUsername orders the results by the username field.
func ByUsername(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUsername, opts...).ToFunc()
}
// ByDid orders the results by the did field.
func ByDid(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDid, opts...).ToFunc()
}
// ByMember orders the results by the member field.
func ByMember(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldMember, opts...).ToFunc()
}
// ByBook orders the results by the book field.
func ByBook(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldBook, opts...).ToFunc()
}
// ByManga orders the results by the manga field.
func ByManga(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldManga, opts...).ToFunc()
}
// ByBadge orders the results by the badge field.
func ByBadge(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldBadge, opts...).ToFunc()
}
// ByBsky orders the results by the bsky field.
func ByBsky(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldBsky, opts...).ToFunc()
}
// ByMastodon orders the results by the mastodon field.
func ByMastodon(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldMastodon, opts...).ToFunc()
}
// ByDelete orders the results by the delete field.
func ByDelete(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDelete, opts...).ToFunc()
}
// ByHandle orders the results by the handle field.
func ByHandle(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldHandle, opts...).ToFunc()
}
// ByToken orders the results by the token field.
func ByToken(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldToken, opts...).ToFunc()
}
// ByPassword orders the results by the password field.
func ByPassword(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPassword, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByUpdatedAt orders the results by the updated_at field.
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
}
// ByRaidAt orders the results by the raid_at field.
func ByRaidAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldRaidAt, opts...).ToFunc()
}
// ByServerAt orders the results by the server_at field.
func ByServerAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldServerAt, opts...).ToFunc()
}
// ByEggAt orders the results by the egg_at field.
func ByEggAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldEggAt, opts...).ToFunc()
}
// ByLuck orders the results by the luck field.
func ByLuck(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLuck, opts...).ToFunc()
}
// ByLuckAt orders the results by the luck_at field.
func ByLuckAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLuckAt, opts...).ToFunc()
}
// ByLike orders the results by the like field.
func ByLike(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLike, opts...).ToFunc()
}
// ByLikeRank orders the results by the like_rank field.
func ByLikeRank(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLikeRank, opts...).ToFunc()
}
// ByLikeAt orders the results by the like_at field.
func ByLikeAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLikeAt, opts...).ToFunc()
}
// ByFav orders the results by the fav field.
func ByFav(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldFav, opts...).ToFunc()
}
// ByTen orders the results by the ten field.
func ByTen(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldTen, opts...).ToFunc()
}
// ByTenSu orders the results by the ten_su field.
func ByTenSu(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldTenSu, opts...).ToFunc()
}
// ByTenKai orders the results by the ten_kai field.
func ByTenKai(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldTenKai, opts...).ToFunc()
}
// ByAiten orders the results by the aiten field.
func ByAiten(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldAiten, opts...).ToFunc()
}
// ByTenCard orders the results by the ten_card field.
func ByTenCard(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldTenCard, opts...).ToFunc()
}
// ByTenDelete orders the results by the ten_delete field.
func ByTenDelete(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldTenDelete, opts...).ToFunc()
}
// ByTenPost orders the results by the ten_post field.
func ByTenPost(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldTenPost, opts...).ToFunc()
}
// ByTenGet orders the results by the ten_get field.
func ByTenGet(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldTenGet, opts...).ToFunc()
}
// ByTenAt orders the results by the ten_at field.
func ByTenAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldTenAt, opts...).ToFunc()
}
// ByNext orders the results by the next field.
func ByNext(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldNext, opts...).ToFunc()
}
// ByRoom orders the results by the room field.
func ByRoom(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldRoom, opts...).ToFunc()
}
// ByModel orders the results by the model field.
func ByModel(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldModel, opts...).ToFunc()
}
// ByModelAt orders the results by the model_at field.
func ByModelAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldModelAt, opts...).ToFunc()
}
// ByModelAttack orders the results by the model_attack field.
func ByModelAttack(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldModelAttack, opts...).ToFunc()
}
// ByModelLimit orders the results by the model_limit field.
func ByModelLimit(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldModelLimit, opts...).ToFunc()
}
// ByModelSkill orders the results by the model_skill field.
func ByModelSkill(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldModelSkill, opts...).ToFunc()
}
// ByModelMode orders the results by the model_mode field.
func ByModelMode(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldModelMode, opts...).ToFunc()
}
// ByModelCritical orders the results by the model_critical field.
func ByModelCritical(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldModelCritical, opts...).ToFunc()
}
// ByModelCriticalD orders the results by the model_critical_d field.
func ByModelCriticalD(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldModelCriticalD, opts...).ToFunc()
}
// ByGame orders the results by the game field.
func ByGame(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldGame, opts...).ToFunc()
}
// ByGameTest orders the results by the game_test field.
func ByGameTest(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldGameTest, opts...).ToFunc()
}
// ByGameEnd orders the results by the game_end field.
func ByGameEnd(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldGameEnd, opts...).ToFunc()
}
// ByGameAccount orders the results by the game_account field.
func ByGameAccount(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldGameAccount, opts...).ToFunc()
}
// ByGameLv orders the results by the game_lv field.
func ByGameLv(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldGameLv, opts...).ToFunc()
}
// ByCardCount orders the results by card count.
func ByCardCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newCardStep(), opts...)
}
}
// ByCard orders the results by card terms.
func ByCard(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newCardStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByUeCount orders the results by ue count.
func ByUeCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newUeStep(), opts...)
}
}
// ByUe orders the results by ue terms.
func ByUe(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUeStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newCardStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(CardInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, CardTable, CardColumn),
)
}
func newUeStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UeInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, UeTable, UeColumn),
)
}

2504
ent/user/where.go Normal file

File diff suppressed because it is too large Load Diff

1171
ent/user_create.go Normal file

File diff suppressed because it is too large Load Diff

88
ent/user_delete.go Normal file
View File

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

686
ent/user_query.go Normal file
View File

@@ -0,0 +1,686 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"api/ent/card"
"api/ent/predicate"
"api/ent/ue"
"api/ent/user"
"context"
"database/sql/driver"
"fmt"
"math"
"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 []user.OrderOption
inters []Interceptor
predicates []predicate.User
withCard *CardQuery
withUe *UeQuery
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 ...user.OrderOption) *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
}
// QueryUe chains the current query on the "ue" edge.
func (uq *UserQuery) QueryUe() *UeQuery {
query := (&UeClient{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(ue.Table, ue.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, user.UeTable, user.UeColumn),
)
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([]user.OrderOption{}, uq.order...),
inters: append([]Interceptor{}, uq.inters...),
predicates: append([]predicate.User{}, uq.predicates...),
withCard: uq.withCard.Clone(),
withUe: uq.withUe.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
}
// WithUe tells the query-builder to eager-load the nodes that are connected to
// the "ue" edge. The optional arguments are used to configure the query builder of the edge.
func (uq *UserQuery) WithUe(opts ...func(*UeQuery)) *UserQuery {
query := (&UeClient{config: uq.config}).Query()
for _, opt := range opts {
opt(query)
}
uq.withUe = 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 = [2]bool{
uq.withCard != nil,
uq.withUe != 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
}
}
if query := uq.withUe; query != nil {
if err := uq.loadUe(ctx, query, nodes,
func(n *User) { n.Edges.Ue = []*Ue{} },
func(n *User, e *Ue) { n.Edges.Ue = append(n.Edges.Ue, 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(s.C(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 referenced foreign-key "user_card" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (uq *UserQuery) loadUe(ctx context.Context, query *UeQuery, nodes []*User, init func(*User), assign func(*User, *Ue)) 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.Ue(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(user.UeColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.user_ue
if fk == nil {
return fmt.Errorf(`foreign-key "user_ue" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "user_ue" 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)
}

3096
ent/user_update.go Normal file

File diff suppressed because it is too large Load Diff

51
go.mod Normal file
View File

@@ -0,0 +1,51 @@
module api
go 1.21
toolchain go1.21.7
//replace ariga.io/ogent => ../../
require (
entgo.io/ent v0.12.2
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/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 (
ariga.io/atlas v0.10.0 // indirect
ariga.io/ogent v0.0.0-20230621041143-ed3e5d4da458 // indirect
entgo.io/contrib v0.4.5 // indirect
github.com/agext/levenshtein v1.2.3 // indirect
github.com/apparentlymart/go-textseg/v13 v13.0.0 // 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-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/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/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/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.9.0 // indirect
golang.org/x/sync v0.1.0 // indirect
golang.org/x/sys v0.6.0 // indirect
golang.org/x/text v0.8.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)

130
go.sum Normal file
View File

@@ -0,0 +1,130 @@
ariga.io/atlas v0.9.2-0.20230303073438-03a4779a6338 h1:8kmSV3mbQKn0niZ/EdE11uhFvFKiW1VlaqVBIYOyahM=
ariga.io/atlas v0.9.2-0.20230303073438-03a4779a6338/go.mod h1:T230JFcENj4ZZzMkZrXFDSkv+2kXkUgpJ5FQQ5hMcKU=
ariga.io/atlas v0.10.0 h1:B1aCP6gSDQET6j8ybn7m6MArjQuoLH5d4DQBT+NP5k8=
ariga.io/atlas v0.10.0/go.mod h1:+TR129FJZ5Lvzms6dvCeGWh1yR6hMvmXBhug4hrNIGk=
ariga.io/ogent v0.0.0-20230621041143-ed3e5d4da458 h1:FShFeMszKX8VcySiTRgshmj98jQWMv2GjQgMJcHJJi4=
ariga.io/ogent v0.0.0-20230621041143-ed3e5d4da458/go.mod h1:95vCbvAYAW6NsWUrSL23k2SQykuf/yjellmwV1X+svI=
entgo.io/contrib v0.4.5 h1:BFaOHwFLE8WZjVJadP0XHCIaxgcC1BAtUvAyw7M/GHk=
entgo.io/contrib v0.4.5/go.mod h1:wpZyq2DJgthugFvDBlaqMXj9mV4/9ebyGEn7xlTVQqE=
entgo.io/ent v0.11.10 h1:iqn32ybY5HRW3xSAyMNdNKpZhKgMf1Zunsej9yPKUI8=
entgo.io/ent v0.11.10/go.mod h1:mzTZ0trE+jCQw/fnzijbm5Mck/l8Gbg7gC/+L1COyzM=
entgo.io/ent v0.12.2 h1:Ndl/JvCX76xCtUDlrUfMnOKBRodAtxE5yfGYxjbOxmM=
entgo.io/ent v0.12.2/go.mod h1:OA1Y5bNE8EtlxKv4IyzWwt4jgvGbkoKMcwp668iEKQE=
github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60=
github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo=
github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw=
github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo=
github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A=
github.com/benbjohnson/clock v1.3.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dlclark/regexp2 v1.8.0 h1:rJD5HeGIT/2b5CDk63FVCwZA3qgYElfg+oQK7uH5pfE=
github.com/dlclark/regexp2 v1.8.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/fatih/color v1.14.1 h1:qfhVLaG5s+nCROl1zJsZRxFeYrHLqWroPOQ8BWiNb4w=
github.com/fatih/color v1.14.1/go.mod h1:2oHN61fhTpgcxD3TSWCgKDiH1+x4OiDVVGH8WlgGZGg=
github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-faster/errors v0.6.1 h1:nNIPOBkprlKzkThvS/0YaX8Zs9KewLCOSFQS5BU06FI=
github.com/go-faster/errors v0.6.1/go.mod h1:5MGV2/2T9yvlrbhe9pD9LO5Z/2zCSq2T8j+Jpi2LAyY=
github.com/go-faster/jx v0.42.0-alpha.1 h1:KRu+ofEoozOsq2qpjwIp2R08vw9w2VqfbV4wtybQZ9U=
github.com/go-faster/jx v0.42.0-alpha.1/go.mod h1:fTSMeBYBKUmGFJaA6EkF658Rrco40FHenmq9fOBpYuM=
github.com/go-faster/yamlx v0.4.1 h1:00RQkZopoLDF1SgBDJVHuN6epTOK7T0TkN427vbvEBk=
github.com/go-faster/yamlx v0.4.1/go.mod h1:QXr/i3Z00jRhskgyWkoGsEdseebd/ZbZEpGS6DJv8oo=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0=
github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-openapi/inflect v0.19.0 h1:9jCH9scKIbHeV9m12SmPilScz6krDxKRasNNSNPXu/4=
github.com/go-openapi/inflect v0.19.0/go.mod h1:lHpZVlpIQqLyKwJ4N+YSc9hchQy/i12fJykb83CRBH4=
github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68=
github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/hcl/v2 v2.15.0 h1:CPDXO6+uORPjKflkWCCwoWc9uRp+zSIPcCQ+BrxV7m8=
github.com/hashicorp/hcl/v2 v2.15.0/go.mod h1:JRmR89jycNkrrqnMmvPDMd56n1rQJ2Q6KocSLCMCXng=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348 h1:MtvEpTB6LX3vkb4ax0b5D2DHbNAUsen0Gx5wZoq3lV4=
github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng=
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y=
github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0=
github.com/ogen-go/ogen v0.59.0 h1:9aSSZ1KCLJIcRyjkO7IHrG0vAI6l1BO877LwTbMcX+k=
github.com/ogen-go/ogen v0.59.0/go.mod h1:0MHLcWEbxwdvR+R9E05paQSRh/2vHtVSJgKqmwYyW8M=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys=
github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
github.com/stoewer/go-strcase v1.2.0 h1:Z2iHWqGXH00XYgqDmNgQbIBxf3wrNq0F3feEy0ainaU=
github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/zclconf/go-cty v1.12.1 h1:PcupnljUm9EIvbgSHQnHhUr3fO6oFmkOrvs2BAFNXXY=
github.com/zclconf/go-cty v1.12.1/go.mod h1:s9IfD1LK5ccNMSWCVFCE2rJfHiZgi7JijgeWIMfhLvA=
go.opentelemetry.io/otel v1.13.0 h1:1ZAKnNQKwBBxFtww/GwxNUyTf0AxkZzrukO8MeXqe4Y=
go.opentelemetry.io/otel v1.13.0/go.mod h1:FH3RtdZCzRkJYFTCsAKDy9l/XYjMdNv6QrkFFB8DvVg=
go.opentelemetry.io/otel/metric v0.36.0 h1:t0lgGI+L68QWt3QtOIlqM9gXoxqxWLhZ3R/e5oOAY0Q=
go.opentelemetry.io/otel/metric v0.36.0/go.mod h1:wKVw57sd2HdSZAzyfOM9gTqqE8v7CbqWsYL6AyrH9qk=
go.opentelemetry.io/otel/trace v1.13.0 h1:CBgRZ6ntv+Amuj1jDsMhZtlAPT6gbyIRdaIzFhfBSdY=
go.opentelemetry.io/otel/trace v1.13.0/go.mod h1:muCvmmO9KKpvuXSf3KKAXXB2ygNYHQ+ZfI5X08d3tds=
go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ=
go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI=
go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=
go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60=
go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg=
golang.org/x/exp v0.0.0-20230206171751-46f607a40771 h1:xP7rWLUr1e1n2xkK5YB4LI0hPEy3LJC6Wk+D4pGlOJg=
golang.org/x/exp v0.0.0-20230206171751-46f607a40771/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.9.0 h1:KENHtAZL2y3NLMYZeHY9DW8HW8V+kQyJsY/V9JlKvCs=
golang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ=
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68=
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/tools v0.7.0 h1:W4OVu8VVOaIO0yzWMNdepAulS7YfoS3Zabrm8DOXXU4=
golang.org/x/tools v0.7.0/go.mod h1:4pg6aUX35JBAogB10C9AtvVL+qowtN4pT3CGSQex14s=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

Binary file not shown.

Before

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

82
main.go Normal file
View File

@@ -0,0 +1,82 @@
package main
import (
"context"
"log"
"net/http"
"api/ent"
"api/ent/ogent"
"entgo.io/ent/dialect"
_ "github.com/mattn/go-sqlite3"
"entgo.io/ent/dialect/sql/schema"
"time"
)
type User struct {
username string `json:"username"`
created_at time.Time `json:"created_at"`
}
type handler struct {
*ogent.OgentHandler
client *ent.Client
}
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) {
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.CreatedAt.Add(time.Hour * 24 * 1).In(jst)
ff := f.Format("20060102")
fff := u_body.Next
if tt < fff {
error := h.client.User.UpdateOneID(params.ID).SetNext(ff).Exec(ctx)
return (error)
}
error := h.client.User.UpdateOneID(params.ID).SetUpdatedAt(t).Exec(ctx)
return (error)
}
func main() {
// Create ent client.
client, err := ent.Open(dialect.SQLite, "file:/app/data/new.sqlite?_fk=1")
//client, err := ent.Open(dialect.SQLite, "file:data?mode=memory&cache=shared&_fk=1")
if err != nil {
log.Fatal(err)
}
// Run the migrations.
//if err := client.Schema.Create(context.Background()); err != nil {
// log.Fatal(err)
//}
ctx := context.Background()
err = client.Schema.Create(ctx, schema.WithAtlas(true))
if err != nil {
log.Fatalf("failed creating schema resources: %v", err)
}
// Create the handler.
h := handler{
OgentHandler: ogent.NewOgentHandler(client),
client: client,
}
// Start listening.
srv, err := ogent.NewServer(h)
//srv,err := ogent.NewServer(ogent.NewOgentHandler(client))
if err != nil {
log.Fatal(err)
}
if err := http.ListenAndServe(":8080", srv); err != nil {
log.Fatal(err)
}
}

3
openapi/.gitignore vendored
View File

@@ -1,3 +0,0 @@
/target/
**/*.rs.bk
Cargo.lock

View File

@@ -1,23 +0,0 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@@ -1,85 +0,0 @@
.gitignore
.travis.yml
Cargo.toml
README.md
docs/Card.md
docs/CardApi.md
docs/CardCreate.md
docs/CardList.md
docs/CardOwnerRead.md
docs/CardRead.md
docs/CardUpdate.md
docs/CreateCardRequest.md
docs/CreateGroupRequest.md
docs/CreateUeRequest.md
docs/CreateUserRequest.md
docs/Group.md
docs/GroupApi.md
docs/GroupCreate.md
docs/GroupList.md
docs/GroupRead.md
docs/GroupUpdate.md
docs/GroupUsersList.md
docs/ListCard400Response.md
docs/Ue.md
docs/UeApi.md
docs/UeCreate.md
docs/UeList.md
docs/UeOwnerRead.md
docs/UeRead.md
docs/UeUpdate.md
docs/UpdateCardRequest.md
docs/UpdateGroupRequest.md
docs/UpdateUeRequest.md
docs/UpdateUserRequest.md
docs/User.md
docs/UserApi.md
docs/UserCardList.md
docs/UserCreate.md
docs/UserList.md
docs/UserRead.md
docs/UserUeList.md
docs/UserUpdate.md
git_push.sh
src/apis/card_api.rs
src/apis/configuration.rs
src/apis/group_api.rs
src/apis/mod.rs
src/apis/ue_api.rs
src/apis/user_api.rs
src/lib.rs
src/models/card.rs
src/models/card_create.rs
src/models/card_list.rs
src/models/card_owner_read.rs
src/models/card_read.rs
src/models/card_update.rs
src/models/create_card_request.rs
src/models/create_group_request.rs
src/models/create_ue_request.rs
src/models/create_user_request.rs
src/models/group.rs
src/models/group_create.rs
src/models/group_list.rs
src/models/group_read.rs
src/models/group_update.rs
src/models/group_users_list.rs
src/models/list_card_400_response.rs
src/models/mod.rs
src/models/ue.rs
src/models/ue_create.rs
src/models/ue_list.rs
src/models/ue_owner_read.rs
src/models/ue_read.rs
src/models/ue_update.rs
src/models/update_card_request.rs
src/models/update_group_request.rs
src/models/update_ue_request.rs
src/models/update_user_request.rs
src/models/user.rs
src/models/user_card_list.rs
src/models/user_create.rs
src/models/user_list.rs
src/models/user_read.rs
src/models/user_ue_list.rs
src/models/user_update.rs

View File

@@ -1 +0,0 @@
7.4.0

View File

@@ -1 +0,0 @@
language: rust

View File

@@ -1,19 +0,0 @@
[package]
name = "openapi"
version = "0.1.0"
authors = ["OpenAPI Generator team and contributors"]
description = "This is an auto generated API description made out of an Ent schema definition"
# Override this license by providing a License Object in the OpenAPI.
license = "Unlicense"
edition = "2018"
[dependencies]
serde = "^1.0"
serde_derive = "^1.0"
serde_with = "^2.0"
serde_json = "^1.0"
url = "^2.2"
uuid = { version = "^1.0", features = ["serde", "v4"] }
[dependencies.reqwest]
version = "^0.11"
features = ["json", "multipart"]

View File

@@ -1,105 +0,0 @@
# Rust API client for openapi
This is an auto generated API description made out of an Ent schema definition
## Overview
This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://openapis.org) from a remote server, you can easily generate an API client.
- API version: 0.1.0
- Package version: 0.1.0
- Generator version: 7.4.0
- Build package: `org.openapitools.codegen.languages.RustClientCodegen`
## Installation
Put the package under your project folder in a directory named `openapi` and add the following to `Cargo.toml` under `[dependencies]`:
```
openapi = { path = "./openapi" }
```
## Documentation for API Endpoints
All URIs are relative to *http://localhost*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*CardApi* | [**create_card**](docs/CardApi.md#create_card) | **POST** /cards | Create a new Card
*CardApi* | [**delete_card**](docs/CardApi.md#delete_card) | **DELETE** /cards/{id} | Deletes a Card by ID
*CardApi* | [**draw_done**](docs/CardApi.md#draw_done) | **PUT** /cards/{id}/d | Draws a card item as done.
*CardApi* | [**draw_start**](docs/CardApi.md#draw_start) | **PATCH** /users/{id}/card/start | Draws a card item as done.
*CardApi* | [**list_card**](docs/CardApi.md#list_card) | **GET** /cards | List Cards
*CardApi* | [**read_card**](docs/CardApi.md#read_card) | **GET** /cards/{id} | Find a Card by ID
*CardApi* | [**read_card_owner**](docs/CardApi.md#read_card_owner) | **GET** /cards/{id}/owner | Find the attached User
*CardApi* | [**update_card**](docs/CardApi.md#update_card) | **PATCH** /cards/{id} | Updates a Card
*GroupApi* | [**create_group**](docs/GroupApi.md#create_group) | **POST** /groups | Create a new Group
*GroupApi* | [**delete_group**](docs/GroupApi.md#delete_group) | **DELETE** /groups/{id} | Deletes a Group by ID
*GroupApi* | [**list_group**](docs/GroupApi.md#list_group) | **GET** /groups | List Groups
*GroupApi* | [**list_group_users**](docs/GroupApi.md#list_group_users) | **GET** /groups/{id}/users | List attached Users
*GroupApi* | [**read_group**](docs/GroupApi.md#read_group) | **GET** /groups/{id} | Find a Group by ID
*GroupApi* | [**update_group**](docs/GroupApi.md#update_group) | **PATCH** /groups/{id} | Updates a Group
*UeApi* | [**create_ue**](docs/UeApi.md#create_ue) | **POST** /ues | Create a new Ue
*UeApi* | [**delete_ue**](docs/UeApi.md#delete_ue) | **DELETE** /ues/{id} | Deletes a Ue by ID
*UeApi* | [**list_ue**](docs/UeApi.md#list_ue) | **GET** /ues | List Ues
*UeApi* | [**read_ue**](docs/UeApi.md#read_ue) | **GET** /ues/{id} | Find a Ue by ID
*UeApi* | [**read_ue_owner**](docs/UeApi.md#read_ue_owner) | **GET** /ues/{id}/owner | Find the attached User
*UeApi* | [**update_ue**](docs/UeApi.md#update_ue) | **PATCH** /ues/{id} | Updates a Ue
*UserApi* | [**create_user**](docs/UserApi.md#create_user) | **POST** /users | Create a new User
*UserApi* | [**delete_user**](docs/UserApi.md#delete_user) | **DELETE** /users/{id} | Deletes a User by ID
*UserApi* | [**list_user**](docs/UserApi.md#list_user) | **GET** /users | List Users
*UserApi* | [**list_user_card**](docs/UserApi.md#list_user_card) | **GET** /users/{id}/card | List attached Cards
*UserApi* | [**list_user_ue**](docs/UserApi.md#list_user_ue) | **GET** /users/{id}/ue | List attached Ues
*UserApi* | [**read_user**](docs/UserApi.md#read_user) | **GET** /users/{id} | Find a User by ID
*UserApi* | [**update_user**](docs/UserApi.md#update_user) | **PATCH** /users/{id} | Updates a User
## Documentation For Models
- [Card](docs/Card.md)
- [CardCreate](docs/CardCreate.md)
- [CardList](docs/CardList.md)
- [CardOwnerRead](docs/CardOwnerRead.md)
- [CardRead](docs/CardRead.md)
- [CardUpdate](docs/CardUpdate.md)
- [CreateCardRequest](docs/CreateCardRequest.md)
- [CreateGroupRequest](docs/CreateGroupRequest.md)
- [CreateUeRequest](docs/CreateUeRequest.md)
- [CreateUserRequest](docs/CreateUserRequest.md)
- [Group](docs/Group.md)
- [GroupCreate](docs/GroupCreate.md)
- [GroupList](docs/GroupList.md)
- [GroupRead](docs/GroupRead.md)
- [GroupUpdate](docs/GroupUpdate.md)
- [GroupUsersList](docs/GroupUsersList.md)
- [ListCard400Response](docs/ListCard400Response.md)
- [Ue](docs/Ue.md)
- [UeCreate](docs/UeCreate.md)
- [UeList](docs/UeList.md)
- [UeOwnerRead](docs/UeOwnerRead.md)
- [UeRead](docs/UeRead.md)
- [UeUpdate](docs/UeUpdate.md)
- [UpdateCardRequest](docs/UpdateCardRequest.md)
- [UpdateGroupRequest](docs/UpdateGroupRequest.md)
- [UpdateUeRequest](docs/UpdateUeRequest.md)
- [UpdateUserRequest](docs/UpdateUserRequest.md)
- [User](docs/User.md)
- [UserCardList](docs/UserCardList.md)
- [UserCreate](docs/UserCreate.md)
- [UserList](docs/UserList.md)
- [UserRead](docs/UserRead.md)
- [UserUeList](docs/UserUeList.md)
- [UserUpdate](docs/UserUpdate.md)
To get access to the crate's generated documentation, use:
```
cargo doc --open
```
## Author

View File

@@ -1,22 +0,0 @@
# Card
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **i32** | |
**password** | **String** | |
**card** | Option<**i32**> | | [optional]
**skill** | Option<**String**> | | [optional]
**status** | Option<**String**> | | [optional]
**token** | Option<**String**> | | [optional]
**cp** | Option<**i32**> | | [optional]
**url** | Option<**String**> | | [optional]
**count** | Option<**i32**> | | [optional]
**author** | Option<**String**> | | [optional]
**created_at** | Option<**String**> | | [optional]
**owner** | [**models::User**](User.md) | |
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -1,254 +0,0 @@
# \CardApi
All URIs are relative to *http://localhost*
Method | HTTP request | Description
------------- | ------------- | -------------
[**create_card**](CardApi.md#create_card) | **POST** /cards | Create a new Card
[**delete_card**](CardApi.md#delete_card) | **DELETE** /cards/{id} | Deletes a Card by ID
[**draw_done**](CardApi.md#draw_done) | **PUT** /cards/{id}/d | Draws a card item as done.
[**draw_start**](CardApi.md#draw_start) | **PATCH** /users/{id}/card/start | Draws a card item as done.
[**list_card**](CardApi.md#list_card) | **GET** /cards | List Cards
[**read_card**](CardApi.md#read_card) | **GET** /cards/{id} | Find a Card by ID
[**read_card_owner**](CardApi.md#read_card_owner) | **GET** /cards/{id}/owner | Find the attached User
[**update_card**](CardApi.md#update_card) | **PATCH** /cards/{id} | Updates a Card
## create_card
> models::CardCreate create_card(create_card_request)
Create a new Card
Creates a new Card and persists it to storage.
### Parameters
Name | Type | Description | Required | Notes
------------- | ------------- | ------------- | ------------- | -------------
**create_card_request** | [**CreateCardRequest**](CreateCardRequest.md) | Card to create | [required] |
### Return type
[**models::CardCreate**](CardCreate.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
## delete_card
> delete_card(id)
Deletes a Card by ID
Deletes the Card with the requested ID.
### Parameters
Name | Type | Description | Required | Notes
------------- | ------------- | ------------- | ------------- | -------------
**id** | **i32** | ID of the Card | [required] |
### Return type
(empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
## draw_done
> draw_done(id)
Draws a card item as done.
### Parameters
Name | Type | Description | Required | Notes
------------- | ------------- | ------------- | ------------- | -------------
**id** | **i32** | | [required] |
### Return type
(empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
## draw_start
> draw_start(id)
Draws a card item as done.
### Parameters
Name | Type | Description | Required | Notes
------------- | ------------- | ------------- | ------------- | -------------
**id** | **i32** | | [required] |
### Return type
(empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
## list_card
> Vec<models::CardList> list_card(page, items_per_page)
List Cards
List Cards.
### Parameters
Name | Type | Description | Required | Notes
------------- | ------------- | ------------- | ------------- | -------------
**page** | Option<**i32**> | what page to render | |
**items_per_page** | Option<**i32**> | item count to render per page | |
### Return type
[**Vec<models::CardList>**](CardList.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
## read_card
> models::CardRead read_card(id)
Find a Card by ID
Finds the Card with the requested ID and returns it.
### Parameters
Name | Type | Description | Required | Notes
------------- | ------------- | ------------- | ------------- | -------------
**id** | **i32** | ID of the Card | [required] |
### Return type
[**models::CardRead**](CardRead.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
## read_card_owner
> models::CardOwnerRead read_card_owner(id)
Find the attached User
Find the attached User of the Card with the given ID
### Parameters
Name | Type | Description | Required | Notes
------------- | ------------- | ------------- | ------------- | -------------
**id** | **i32** | ID of the Card | [required] |
### Return type
[**models::CardOwnerRead**](Card_OwnerRead.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
## update_card
> models::CardUpdate update_card(id, update_card_request)
Updates a Card
Updates a Card and persists changes to storage.
### Parameters
Name | Type | Description | Required | Notes
------------- | ------------- | ------------- | ------------- | -------------
**id** | **i32** | ID of the Card | [required] |
**update_card_request** | [**UpdateCardRequest**](UpdateCardRequest.md) | Card properties to update | [required] |
### Return type
[**models::CardUpdate**](CardUpdate.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View File

@@ -1,19 +0,0 @@
# CardCreate
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **i32** | |
**card** | Option<**i32**> | | [optional]
**skill** | Option<**String**> | | [optional]
**status** | Option<**String**> | | [optional]
**cp** | Option<**i32**> | | [optional]
**url** | Option<**String**> | | [optional]
**count** | Option<**i32**> | | [optional]
**author** | Option<**String**> | | [optional]
**created_at** | Option<**String**> | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -1,19 +0,0 @@
# CardList
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **i32** | |
**card** | Option<**i32**> | | [optional]
**skill** | Option<**String**> | | [optional]
**status** | Option<**String**> | | [optional]
**cp** | Option<**i32**> | | [optional]
**url** | Option<**String**> | | [optional]
**count** | Option<**i32**> | | [optional]
**author** | Option<**String**> | | [optional]
**created_at** | Option<**String**> | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -1,59 +0,0 @@
# CardOwnerRead
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **i32** | |
**username** | **String** | |
**did** | Option<**String**> | | [optional]
**member** | Option<**bool**> | | [optional]
**book** | Option<**bool**> | | [optional]
**manga** | Option<**bool**> | | [optional]
**badge** | Option<**bool**> | | [optional]
**bsky** | Option<**bool**> | | [optional]
**mastodon** | Option<**bool**> | | [optional]
**delete** | Option<**bool**> | | [optional]
**handle** | Option<**bool**> | | [optional]
**created_at** | Option<**String**> | | [optional]
**updated_at** | Option<**String**> | | [optional]
**raid_at** | Option<**String**> | | [optional]
**server_at** | Option<**String**> | | [optional]
**egg_at** | Option<**String**> | | [optional]
**luck** | Option<**i32**> | | [optional]
**luck_at** | Option<**String**> | | [optional]
**like** | Option<**i32**> | | [optional]
**like_rank** | Option<**i32**> | | [optional]
**like_at** | Option<**String**> | | [optional]
**fav** | Option<**i32**> | | [optional]
**ten** | Option<**bool**> | | [optional]
**ten_su** | Option<**i32**> | | [optional]
**ten_kai** | Option<**i32**> | | [optional]
**aiten** | Option<**i32**> | | [optional]
**ten_card** | Option<**String**> | | [optional]
**ten_delete** | Option<**String**> | | [optional]
**ten_post** | Option<**String**> | | [optional]
**ten_get** | Option<**String**> | | [optional]
**ten_at** | Option<**String**> | | [optional]
**next** | Option<**String**> | | [optional]
**room** | Option<**i32**> | | [optional]
**model** | Option<**bool**> | | [optional]
**model_at** | Option<**String**> | | [optional]
**model_attack** | Option<**i32**> | | [optional]
**model_limit** | Option<**i32**> | | [optional]
**model_skill** | Option<**i32**> | | [optional]
**model_mode** | Option<**i32**> | | [optional]
**model_critical** | Option<**i32**> | | [optional]
**model_critical_d** | Option<**i32**> | | [optional]
**game** | Option<**bool**> | | [optional]
**game_test** | Option<**bool**> | | [optional]
**game_end** | Option<**bool**> | | [optional]
**game_account** | Option<**bool**> | | [optional]
**game_lv** | Option<**i32**> | | [optional]
**coin** | Option<**i32**> | | [optional]
**coin_open** | Option<**bool**> | | [optional]
**coin_at** | Option<**String**> | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -1,19 +0,0 @@
# CardRead
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **i32** | |
**card** | Option<**i32**> | | [optional]
**skill** | Option<**String**> | | [optional]
**status** | Option<**String**> | | [optional]
**cp** | Option<**i32**> | | [optional]
**url** | Option<**String**> | | [optional]
**count** | Option<**i32**> | | [optional]
**author** | Option<**String**> | | [optional]
**created_at** | Option<**String**> | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -1,19 +0,0 @@
# CardUpdate
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **i32** | |
**card** | Option<**i32**> | | [optional]
**skill** | Option<**String**> | | [optional]
**status** | Option<**String**> | | [optional]
**cp** | Option<**i32**> | | [optional]
**url** | Option<**String**> | | [optional]
**count** | Option<**i32**> | | [optional]
**author** | Option<**String**> | | [optional]
**created_at** | Option<**String**> | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -1,21 +0,0 @@
# CreateCardRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**password** | **String** | |
**card** | Option<**i32**> | | [optional]
**skill** | Option<**String**> | | [optional]
**status** | Option<**String**> | | [optional]
**token** | Option<**String**> | | [optional]
**cp** | Option<**i32**> | | [optional]
**url** | Option<**String**> | | [optional]
**count** | Option<**i32**> | | [optional]
**author** | Option<**String**> | | [optional]
**created_at** | Option<**String**> | | [optional]
**owner** | **i32** | |
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -1,13 +0,0 @@
# CreateGroupRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**name** | **String** | |
**password** | **String** | |
**users** | Option<**Vec<i32>**> | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -1,30 +0,0 @@
# CreateUeRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**limit** | Option<**bool**> | | [optional]
**limit_boss** | Option<**bool**> | | [optional]
**limit_item** | Option<**bool**> | | [optional]
**password** | **String** | |
**lv** | Option<**i32**> | | [optional]
**lv_point** | Option<**i32**> | | [optional]
**model** | Option<**i32**> | | [optional]
**sword** | Option<**i32**> | | [optional]
**card** | Option<**i32**> | | [optional]
**mode** | Option<**String**> | | [optional]
**token** | Option<**String**> | | [optional]
**cp** | Option<**i32**> | | [optional]
**count** | Option<**i32**> | | [optional]
**location_x** | Option<**i32**> | | [optional]
**location_y** | Option<**i32**> | | [optional]
**location_z** | Option<**i32**> | | [optional]
**location_n** | Option<**i32**> | | [optional]
**author** | Option<**String**> | | [optional]
**created_at** | Option<**String**> | | [optional]
**owner** | **i32** | |
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -1,62 +0,0 @@
# CreateUserRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**username** | **String** | |
**did** | Option<**String**> | | [optional]
**member** | Option<**bool**> | | [optional]
**book** | Option<**bool**> | | [optional]
**manga** | Option<**bool**> | | [optional]
**badge** | Option<**bool**> | | [optional]
**bsky** | Option<**bool**> | | [optional]
**mastodon** | Option<**bool**> | | [optional]
**delete** | Option<**bool**> | | [optional]
**handle** | Option<**bool**> | | [optional]
**token** | Option<**String**> | | [optional]
**password** | **String** | |
**created_at** | Option<**String**> | | [optional]
**updated_at** | Option<**String**> | | [optional]
**raid_at** | Option<**String**> | | [optional]
**server_at** | Option<**String**> | | [optional]
**egg_at** | Option<**String**> | | [optional]
**luck** | Option<**i32**> | | [optional]
**luck_at** | Option<**String**> | | [optional]
**like** | Option<**i32**> | | [optional]
**like_rank** | Option<**i32**> | | [optional]
**like_at** | Option<**String**> | | [optional]
**fav** | Option<**i32**> | | [optional]
**ten** | Option<**bool**> | | [optional]
**ten_su** | Option<**i32**> | | [optional]
**ten_kai** | Option<**i32**> | | [optional]
**aiten** | Option<**i32**> | | [optional]
**ten_card** | Option<**String**> | | [optional]
**ten_delete** | Option<**String**> | | [optional]
**ten_post** | Option<**String**> | | [optional]
**ten_get** | Option<**String**> | | [optional]
**ten_at** | Option<**String**> | | [optional]
**next** | Option<**String**> | | [optional]
**room** | Option<**i32**> | | [optional]
**model** | Option<**bool**> | | [optional]
**model_at** | Option<**String**> | | [optional]
**model_attack** | Option<**i32**> | | [optional]
**model_limit** | Option<**i32**> | | [optional]
**model_skill** | Option<**i32**> | | [optional]
**model_mode** | Option<**i32**> | | [optional]
**model_critical** | Option<**i32**> | | [optional]
**model_critical_d** | Option<**i32**> | | [optional]
**game** | Option<**bool**> | | [optional]
**game_test** | Option<**bool**> | | [optional]
**game_end** | Option<**bool**> | | [optional]
**game_account** | Option<**bool**> | | [optional]
**game_lv** | Option<**i32**> | | [optional]
**coin** | Option<**i32**> | | [optional]
**coin_open** | Option<**bool**> | | [optional]
**coin_at** | Option<**String**> | | [optional]
**card** | Option<**Vec<i32>**> | | [optional]
**ue** | Option<**Vec<i32>**> | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -1,14 +0,0 @@
# Group
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **i32** | |
**name** | **String** | |
**password** | **String** | |
**users** | Option<[**Vec<models::User>**](User.md)> | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@@ -1,198 +0,0 @@
# \GroupApi
All URIs are relative to *http://localhost*
Method | HTTP request | Description
------------- | ------------- | -------------
[**create_group**](GroupApi.md#create_group) | **POST** /groups | Create a new Group
[**delete_group**](GroupApi.md#delete_group) | **DELETE** /groups/{id} | Deletes a Group by ID
[**list_group**](GroupApi.md#list_group) | **GET** /groups | List Groups
[**list_group_users**](GroupApi.md#list_group_users) | **GET** /groups/{id}/users | List attached Users
[**read_group**](GroupApi.md#read_group) | **GET** /groups/{id} | Find a Group by ID
[**update_group**](GroupApi.md#update_group) | **PATCH** /groups/{id} | Updates a Group
## create_group
> models::GroupCreate create_group(create_group_request)
Create a new Group
Creates a new Group and persists it to storage.
### Parameters
Name | Type | Description | Required | Notes
------------- | ------------- | ------------- | ------------- | -------------
**create_group_request** | [**CreateGroupRequest**](CreateGroupRequest.md) | Group to create | [required] |
### Return type
[**models::GroupCreate**](GroupCreate.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
## delete_group
> delete_group(id)
Deletes a Group by ID
Deletes the Group with the requested ID.
### Parameters
Name | Type | Description | Required | Notes
------------- | ------------- | ------------- | ------------- | -------------
**id** | **i32** | ID of the Group | [required] |
### Return type
(empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
## list_group
> Vec<models::GroupList> list_group(page, items_per_page)
List Groups
List Groups.
### Parameters
Name | Type | Description | Required | Notes
------------- | ------------- | ------------- | ------------- | -------------
**page** | Option<**i32**> | what page to render | |
**items_per_page** | Option<**i32**> | item count to render per page | |
### Return type
[**Vec<models::GroupList>**](GroupList.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
## list_group_users
> Vec<models::GroupUsersList> list_group_users(id, page, items_per_page)
List attached Users
List attached Users.
### Parameters
Name | Type | Description | Required | Notes
------------- | ------------- | ------------- | ------------- | -------------
**id** | **i32** | ID of the Group | [required] |
**page** | Option<**i32**> | what page to render | |
**items_per_page** | Option<**i32**> | item count to render per page | |
### Return type
[**Vec<models::GroupUsersList>**](Group_UsersList.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
## read_group
> models::GroupRead read_group(id)
Find a Group by ID
Finds the Group with the requested ID and returns it.
### Parameters
Name | Type | Description | Required | Notes
------------- | ------------- | ------------- | ------------- | -------------
**id** | **i32** | ID of the Group | [required] |
### Return type
[**models::GroupRead**](GroupRead.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
## update_group
> models::GroupUpdate update_group(id, update_group_request)
Updates a Group
Updates a Group and persists changes to storage.
### Parameters
Name | Type | Description | Required | Notes
------------- | ------------- | ------------- | ------------- | -------------
**id** | **i32** | ID of the Group | [required] |
**update_group_request** | [**UpdateGroupRequest**](UpdateGroupRequest.md) | Group properties to update | [required] |
### Return type
[**models::GroupUpdate**](GroupUpdate.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

View File

@@ -1,12 +0,0 @@
# GroupCreate
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **i32** | |
**name** | **String** | |
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

Some files were not shown because too many files have changed in this diff Show More