Commit 5906f9ab authored by yangjianbo's avatar yangjianbo
Browse files

fix(数据层): 修复数据完整性与仓储一致性问题

## 数据完整性修复 (fix-critical-data-integrity)
- 添加 error_translate.go 统一错误转换层
- 修复 nil 输入和 NotFound 错误处理
- 增强仓储层错误一致性

## 仓储一致性修复 (fix-high-repository-consistency)
- Group schema 添加 default_validity_days 字段
- Account schema 添加 proxy edge 关联
- 新增 UsageLog ent schema 定义
- 修复 UpdateBalance/UpdateConcurrency 受影响行数校验

## 数据卫生修复 (fix-medium-data-hygiene)
- UserSubscription 添加软删除支持 (SoftDeleteMixin)
- RedeemCode/Setting 添加硬删除策略文档
- account_groups/user_allowed_groups 的 created_at 声明 timestamptz
- 停止写入 legacy users.allowed_groups 列
- 新增迁移: 011-014 (索引优化、软删除、孤立数据审计、列清理)

## 测试补充
- 添加 UserSubscription 软删除测试
- 添加迁移回归测试
- 添加 NotFound 错误测试

🤖 Generated with [Claude Code](https://claude.com/claude-code

)
Co-Authored-By: default avatarClaude Opus 4.5 <noreply@anthropic.com>
parent 820bb16c
......@@ -116,3 +116,4 @@ openspec/
docs/
code-reviews/
AGENTS.md
backend/cmd/server/server
......@@ -70,7 +70,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
billingCacheService := service.NewBillingCacheService(billingCache, userRepository, userSubscriptionRepository, configConfig)
subscriptionService := service.NewSubscriptionService(groupRepository, userSubscriptionRepository, billingCacheService)
redeemCache := repository.NewRedeemCache(redisClient)
redeemService := service.NewRedeemService(redeemCodeRepository, userRepository, subscriptionService, redeemCache, billingCacheService)
redeemService := service.NewRedeemService(redeemCodeRepository, userRepository, subscriptionService, redeemCache, billingCacheService, client)
redeemHandler := handler.NewRedeemHandler(redeemService)
subscriptionHandler := handler.NewSubscriptionHandler(subscriptionService)
dashboardService := service.NewDashboardService(usageLogRepository)
......
......@@ -11,6 +11,7 @@ import (
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/Wei-Shaw/sub2api/ent/account"
"github.com/Wei-Shaw/sub2api/ent/proxy"
)
// Account is the model entity for the Account schema.
......@@ -70,11 +71,15 @@ type Account struct {
type AccountEdges struct {
// Groups holds the value of the groups edge.
Groups []*Group `json:"groups,omitempty"`
// Proxy holds the value of the proxy edge.
Proxy *Proxy `json:"proxy,omitempty"`
// UsageLogs holds the value of the usage_logs edge.
UsageLogs []*UsageLog `json:"usage_logs,omitempty"`
// AccountGroups holds the value of the account_groups edge.
AccountGroups []*AccountGroup `json:"account_groups,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
loadedTypes [4]bool
}
// GroupsOrErr returns the Groups value or an error if the edge
......@@ -86,10 +91,30 @@ func (e AccountEdges) GroupsOrErr() ([]*Group, error) {
return nil, &NotLoadedError{edge: "groups"}
}
// ProxyOrErr returns the Proxy value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e AccountEdges) ProxyOrErr() (*Proxy, error) {
if e.Proxy != nil {
return e.Proxy, nil
} else if e.loadedTypes[1] {
return nil, &NotFoundError{label: proxy.Label}
}
return nil, &NotLoadedError{edge: "proxy"}
}
// UsageLogsOrErr returns the UsageLogs value or an error if the edge
// was not loaded in eager-loading.
func (e AccountEdges) UsageLogsOrErr() ([]*UsageLog, error) {
if e.loadedTypes[2] {
return e.UsageLogs, nil
}
return nil, &NotLoadedError{edge: "usage_logs"}
}
// AccountGroupsOrErr returns the AccountGroups value or an error if the edge
// was not loaded in eager-loading.
func (e AccountEdges) AccountGroupsOrErr() ([]*AccountGroup, error) {
if e.loadedTypes[1] {
if e.loadedTypes[3] {
return e.AccountGroups, nil
}
return nil, &NotLoadedError{edge: "account_groups"}
......@@ -289,6 +314,16 @@ func (_m *Account) QueryGroups() *GroupQuery {
return NewAccountClient(_m.config).QueryGroups(_m)
}
// QueryProxy queries the "proxy" edge of the Account entity.
func (_m *Account) QueryProxy() *ProxyQuery {
return NewAccountClient(_m.config).QueryProxy(_m)
}
// QueryUsageLogs queries the "usage_logs" edge of the Account entity.
func (_m *Account) QueryUsageLogs() *UsageLogQuery {
return NewAccountClient(_m.config).QueryUsageLogs(_m)
}
// QueryAccountGroups queries the "account_groups" edge of the Account entity.
func (_m *Account) QueryAccountGroups() *AccountGroupQuery {
return NewAccountClient(_m.config).QueryAccountGroups(_m)
......
......@@ -59,6 +59,10 @@ const (
FieldSessionWindowStatus = "session_window_status"
// EdgeGroups holds the string denoting the groups edge name in mutations.
EdgeGroups = "groups"
// EdgeProxy holds the string denoting the proxy edge name in mutations.
EdgeProxy = "proxy"
// EdgeUsageLogs holds the string denoting the usage_logs edge name in mutations.
EdgeUsageLogs = "usage_logs"
// EdgeAccountGroups holds the string denoting the account_groups edge name in mutations.
EdgeAccountGroups = "account_groups"
// Table holds the table name of the account in the database.
......@@ -68,6 +72,20 @@ const (
// GroupsInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupsInverseTable = "groups"
// ProxyTable is the table that holds the proxy relation/edge.
ProxyTable = "accounts"
// ProxyInverseTable is the table name for the Proxy entity.
// It exists in this package in order to avoid circular dependency with the "proxy" package.
ProxyInverseTable = "proxies"
// ProxyColumn is the table column denoting the proxy relation/edge.
ProxyColumn = "proxy_id"
// UsageLogsTable is the table that holds the usage_logs relation/edge.
UsageLogsTable = "usage_logs"
// UsageLogsInverseTable is the table name for the UsageLog entity.
// It exists in this package in order to avoid circular dependency with the "usagelog" package.
UsageLogsInverseTable = "usage_logs"
// UsageLogsColumn is the table column denoting the usage_logs relation/edge.
UsageLogsColumn = "account_id"
// AccountGroupsTable is the table that holds the account_groups relation/edge.
AccountGroupsTable = "account_groups"
// AccountGroupsInverseTable is the table name for the AccountGroup entity.
......@@ -274,6 +292,27 @@ func ByGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
}
}
// ByProxyField orders the results by proxy field.
func ByProxyField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newProxyStep(), sql.OrderByField(field, opts...))
}
}
// ByUsageLogsCount orders the results by usage_logs count.
func ByUsageLogsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newUsageLogsStep(), opts...)
}
}
// ByUsageLogs orders the results by usage_logs terms.
func ByUsageLogs(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUsageLogsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByAccountGroupsCount orders the results by account_groups count.
func ByAccountGroupsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
......@@ -294,6 +333,20 @@ func newGroupsStep() *sqlgraph.Step {
sqlgraph.Edge(sqlgraph.M2M, false, GroupsTable, GroupsPrimaryKey...),
)
}
func newProxyStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ProxyInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, ProxyTable, ProxyColumn),
)
}
func newUsageLogsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UsageLogsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, UsageLogsTable, UsageLogsColumn),
)
}
func newAccountGroupsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
......
......@@ -495,26 +495,6 @@ func ProxyIDNotIn(vs ...int64) predicate.Account {
return predicate.Account(sql.FieldNotIn(FieldProxyID, vs...))
}
// ProxyIDGT applies the GT predicate on the "proxy_id" field.
func ProxyIDGT(v int64) predicate.Account {
return predicate.Account(sql.FieldGT(FieldProxyID, v))
}
// ProxyIDGTE applies the GTE predicate on the "proxy_id" field.
func ProxyIDGTE(v int64) predicate.Account {
return predicate.Account(sql.FieldGTE(FieldProxyID, v))
}
// ProxyIDLT applies the LT predicate on the "proxy_id" field.
func ProxyIDLT(v int64) predicate.Account {
return predicate.Account(sql.FieldLT(FieldProxyID, v))
}
// ProxyIDLTE applies the LTE predicate on the "proxy_id" field.
func ProxyIDLTE(v int64) predicate.Account {
return predicate.Account(sql.FieldLTE(FieldProxyID, v))
}
// ProxyIDIsNil applies the IsNil predicate on the "proxy_id" field.
func ProxyIDIsNil() predicate.Account {
return predicate.Account(sql.FieldIsNull(FieldProxyID))
......@@ -1153,6 +1133,52 @@ func HasGroupsWith(preds ...predicate.Group) predicate.Account {
})
}
// HasProxy applies the HasEdge predicate on the "proxy" edge.
func HasProxy() predicate.Account {
return predicate.Account(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, ProxyTable, ProxyColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasProxyWith applies the HasEdge predicate on the "proxy" edge with a given conditions (other predicates).
func HasProxyWith(preds ...predicate.Proxy) predicate.Account {
return predicate.Account(func(s *sql.Selector) {
step := newProxyStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasUsageLogs applies the HasEdge predicate on the "usage_logs" edge.
func HasUsageLogs() predicate.Account {
return predicate.Account(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, UsageLogsTable, UsageLogsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasUsageLogsWith applies the HasEdge predicate on the "usage_logs" edge with a given conditions (other predicates).
func HasUsageLogsWith(preds ...predicate.UsageLog) predicate.Account {
return predicate.Account(func(s *sql.Selector) {
step := newUsageLogsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasAccountGroups applies the HasEdge predicate on the "account_groups" edge.
func HasAccountGroups() predicate.Account {
return predicate.Account(func(s *sql.Selector) {
......
......@@ -13,6 +13,8 @@ import (
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/account"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/proxy"
"github.com/Wei-Shaw/sub2api/ent/usagelog"
)
// AccountCreate is the builder for creating a Account entity.
......@@ -292,6 +294,26 @@ func (_c *AccountCreate) AddGroups(v ...*Group) *AccountCreate {
return _c.AddGroupIDs(ids...)
}
// SetProxy sets the "proxy" edge to the Proxy entity.
func (_c *AccountCreate) SetProxy(v *Proxy) *AccountCreate {
return _c.SetProxyID(v.ID)
}
// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by IDs.
func (_c *AccountCreate) AddUsageLogIDs(ids ...int64) *AccountCreate {
_c.mutation.AddUsageLogIDs(ids...)
return _c
}
// AddUsageLogs adds the "usage_logs" edges to the UsageLog entity.
func (_c *AccountCreate) AddUsageLogs(v ...*UsageLog) *AccountCreate {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddUsageLogIDs(ids...)
}
// Mutation returns the AccountMutation object of the builder.
func (_c *AccountCreate) Mutation() *AccountMutation {
return _c.mutation
......@@ -495,10 +517,6 @@ func (_c *AccountCreate) createSpec() (*Account, *sqlgraph.CreateSpec) {
_spec.SetField(account.FieldExtra, field.TypeJSON, value)
_node.Extra = value
}
if value, ok := _c.mutation.ProxyID(); ok {
_spec.SetField(account.FieldProxyID, field.TypeInt64, value)
_node.ProxyID = &value
}
if value, ok := _c.mutation.Concurrency(); ok {
_spec.SetField(account.FieldConcurrency, field.TypeInt, value)
_node.Concurrency = value
......@@ -567,6 +585,39 @@ func (_c *AccountCreate) createSpec() (*Account, *sqlgraph.CreateSpec) {
edge.Target.Fields = specE.Fields
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.ProxyIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: account.ProxyTable,
Columns: []string{account.ProxyColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.ProxyID = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.UsageLogsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.UsageLogsTable,
Columns: []string{account.UsageLogsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
......@@ -721,12 +772,6 @@ func (u *AccountUpsert) UpdateProxyID() *AccountUpsert {
return u
}
// AddProxyID adds v to the "proxy_id" field.
func (u *AccountUpsert) AddProxyID(v int64) *AccountUpsert {
u.Add(account.FieldProxyID, v)
return u
}
// ClearProxyID clears the value of the "proxy_id" field.
func (u *AccountUpsert) ClearProxyID() *AccountUpsert {
u.SetNull(account.FieldProxyID)
......@@ -1094,13 +1139,6 @@ func (u *AccountUpsertOne) SetProxyID(v int64) *AccountUpsertOne {
})
}
// AddProxyID adds v to the "proxy_id" field.
func (u *AccountUpsertOne) AddProxyID(v int64) *AccountUpsertOne {
return u.Update(func(s *AccountUpsert) {
s.AddProxyID(v)
})
}
// UpdateProxyID sets the "proxy_id" field to the value that was provided on create.
func (u *AccountUpsertOne) UpdateProxyID() *AccountUpsertOne {
return u.Update(func(s *AccountUpsert) {
......@@ -1676,13 +1714,6 @@ func (u *AccountUpsertBulk) SetProxyID(v int64) *AccountUpsertBulk {
})
}
// AddProxyID adds v to the "proxy_id" field.
func (u *AccountUpsertBulk) AddProxyID(v int64) *AccountUpsertBulk {
return u.Update(func(s *AccountUpsert) {
s.AddProxyID(v)
})
}
// UpdateProxyID sets the "proxy_id" field to the value that was provided on create.
func (u *AccountUpsertBulk) UpdateProxyID() *AccountUpsertBulk {
return u.Update(func(s *AccountUpsert) {
......
......@@ -16,6 +16,8 @@ import (
"github.com/Wei-Shaw/sub2api/ent/accountgroup"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
"github.com/Wei-Shaw/sub2api/ent/proxy"
"github.com/Wei-Shaw/sub2api/ent/usagelog"
)
// AccountQuery is the builder for querying Account entities.
......@@ -26,6 +28,8 @@ type AccountQuery struct {
inters []Interceptor
predicates []predicate.Account
withGroups *GroupQuery
withProxy *ProxyQuery
withUsageLogs *UsageLogQuery
withAccountGroups *AccountGroupQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
......@@ -85,6 +89,50 @@ func (_q *AccountQuery) QueryGroups() *GroupQuery {
return query
}
// QueryProxy chains the current query on the "proxy" edge.
func (_q *AccountQuery) QueryProxy() *ProxyQuery {
query := (&ProxyClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(account.Table, account.FieldID, selector),
sqlgraph.To(proxy.Table, proxy.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, account.ProxyTable, account.ProxyColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryUsageLogs chains the current query on the "usage_logs" edge.
func (_q *AccountQuery) QueryUsageLogs() *UsageLogQuery {
query := (&UsageLogClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(account.Table, account.FieldID, selector),
sqlgraph.To(usagelog.Table, usagelog.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, account.UsageLogsTable, account.UsageLogsColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryAccountGroups chains the current query on the "account_groups" edge.
func (_q *AccountQuery) QueryAccountGroups() *AccountGroupQuery {
query := (&AccountGroupClient{config: _q.config}).Query()
......@@ -300,6 +348,8 @@ func (_q *AccountQuery) Clone() *AccountQuery {
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Account{}, _q.predicates...),
withGroups: _q.withGroups.Clone(),
withProxy: _q.withProxy.Clone(),
withUsageLogs: _q.withUsageLogs.Clone(),
withAccountGroups: _q.withAccountGroups.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
......@@ -318,6 +368,28 @@ func (_q *AccountQuery) WithGroups(opts ...func(*GroupQuery)) *AccountQuery {
return _q
}
// WithProxy tells the query-builder to eager-load the nodes that are connected to
// the "proxy" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *AccountQuery) WithProxy(opts ...func(*ProxyQuery)) *AccountQuery {
query := (&ProxyClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withProxy = query
return _q
}
// WithUsageLogs tells the query-builder to eager-load the nodes that are connected to
// the "usage_logs" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *AccountQuery) WithUsageLogs(opts ...func(*UsageLogQuery)) *AccountQuery {
query := (&UsageLogClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withUsageLogs = query
return _q
}
// WithAccountGroups tells the query-builder to eager-load the nodes that are connected to
// the "account_groups" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *AccountQuery) WithAccountGroups(opts ...func(*AccountGroupQuery)) *AccountQuery {
......@@ -407,8 +479,10 @@ func (_q *AccountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Acco
var (
nodes = []*Account{}
_spec = _q.querySpec()
loadedTypes = [2]bool{
loadedTypes = [4]bool{
_q.withGroups != nil,
_q.withProxy != nil,
_q.withUsageLogs != nil,
_q.withAccountGroups != nil,
}
)
......@@ -437,6 +511,19 @@ func (_q *AccountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Acco
return nil, err
}
}
if query := _q.withProxy; query != nil {
if err := _q.loadProxy(ctx, query, nodes, nil,
func(n *Account, e *Proxy) { n.Edges.Proxy = e }); err != nil {
return nil, err
}
}
if query := _q.withUsageLogs; query != nil {
if err := _q.loadUsageLogs(ctx, query, nodes,
func(n *Account) { n.Edges.UsageLogs = []*UsageLog{} },
func(n *Account, e *UsageLog) { n.Edges.UsageLogs = append(n.Edges.UsageLogs, e) }); err != nil {
return nil, err
}
}
if query := _q.withAccountGroups; query != nil {
if err := _q.loadAccountGroups(ctx, query, nodes,
func(n *Account) { n.Edges.AccountGroups = []*AccountGroup{} },
......@@ -508,6 +595,68 @@ func (_q *AccountQuery) loadGroups(ctx context.Context, query *GroupQuery, nodes
}
return nil
}
func (_q *AccountQuery) loadProxy(ctx context.Context, query *ProxyQuery, nodes []*Account, init func(*Account), assign func(*Account, *Proxy)) error {
ids := make([]int64, 0, len(nodes))
nodeids := make(map[int64][]*Account)
for i := range nodes {
if nodes[i].ProxyID == nil {
continue
}
fk := *nodes[i].ProxyID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(proxy.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 "proxy_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *AccountQuery) loadUsageLogs(ctx context.Context, query *UsageLogQuery, nodes []*Account, init func(*Account), assign func(*Account, *UsageLog)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[int64]*Account)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
if len(query.ctx.Fields) > 0 {
query.ctx.AppendFieldOnce(usagelog.FieldAccountID)
}
query.Where(predicate.UsageLog(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(account.UsageLogsColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.AccountID
node, ok := nodeids[fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "account_id" returned %v for node %v`, fk, n.ID)
}
assign(node, n)
}
return nil
}
func (_q *AccountQuery) loadAccountGroups(ctx context.Context, query *AccountGroupQuery, nodes []*Account, init func(*Account), assign func(*Account, *AccountGroup)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[int64]*Account)
......@@ -564,6 +713,9 @@ func (_q *AccountQuery) querySpec() *sqlgraph.QuerySpec {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
if _q.withProxy != nil {
_spec.Node.AddColumnOnce(account.FieldProxyID)
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
......
......@@ -14,6 +14,8 @@ import (
"github.com/Wei-Shaw/sub2api/ent/account"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
"github.com/Wei-Shaw/sub2api/ent/proxy"
"github.com/Wei-Shaw/sub2api/ent/usagelog"
)
// AccountUpdate is the builder for updating Account entities.
......@@ -111,7 +113,6 @@ func (_u *AccountUpdate) SetExtra(v map[string]interface{}) *AccountUpdate {
// SetProxyID sets the "proxy_id" field.
func (_u *AccountUpdate) SetProxyID(v int64) *AccountUpdate {
_u.mutation.ResetProxyID()
_u.mutation.SetProxyID(v)
return _u
}
......@@ -124,12 +125,6 @@ func (_u *AccountUpdate) SetNillableProxyID(v *int64) *AccountUpdate {
return _u
}
// AddProxyID adds value to the "proxy_id" field.
func (_u *AccountUpdate) AddProxyID(v int64) *AccountUpdate {
_u.mutation.AddProxyID(v)
return _u
}
// ClearProxyID clears the value of the "proxy_id" field.
func (_u *AccountUpdate) ClearProxyID() *AccountUpdate {
_u.mutation.ClearProxyID()
......@@ -381,6 +376,26 @@ func (_u *AccountUpdate) AddGroups(v ...*Group) *AccountUpdate {
return _u.AddGroupIDs(ids...)
}
// SetProxy sets the "proxy" edge to the Proxy entity.
func (_u *AccountUpdate) SetProxy(v *Proxy) *AccountUpdate {
return _u.SetProxyID(v.ID)
}
// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by IDs.
func (_u *AccountUpdate) AddUsageLogIDs(ids ...int64) *AccountUpdate {
_u.mutation.AddUsageLogIDs(ids...)
return _u
}
// AddUsageLogs adds the "usage_logs" edges to the UsageLog entity.
func (_u *AccountUpdate) AddUsageLogs(v ...*UsageLog) *AccountUpdate {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddUsageLogIDs(ids...)
}
// Mutation returns the AccountMutation object of the builder.
func (_u *AccountUpdate) Mutation() *AccountMutation {
return _u.mutation
......@@ -407,6 +422,33 @@ func (_u *AccountUpdate) RemoveGroups(v ...*Group) *AccountUpdate {
return _u.RemoveGroupIDs(ids...)
}
// ClearProxy clears the "proxy" edge to the Proxy entity.
func (_u *AccountUpdate) ClearProxy() *AccountUpdate {
_u.mutation.ClearProxy()
return _u
}
// ClearUsageLogs clears all "usage_logs" edges to the UsageLog entity.
func (_u *AccountUpdate) ClearUsageLogs() *AccountUpdate {
_u.mutation.ClearUsageLogs()
return _u
}
// RemoveUsageLogIDs removes the "usage_logs" edge to UsageLog entities by IDs.
func (_u *AccountUpdate) RemoveUsageLogIDs(ids ...int64) *AccountUpdate {
_u.mutation.RemoveUsageLogIDs(ids...)
return _u
}
// RemoveUsageLogs removes "usage_logs" edges to UsageLog entities.
func (_u *AccountUpdate) RemoveUsageLogs(v ...*UsageLog) *AccountUpdate {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveUsageLogIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *AccountUpdate) Save(ctx context.Context) (int, error) {
if err := _u.defaults(); err != nil {
......@@ -515,15 +557,6 @@ func (_u *AccountUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if value, ok := _u.mutation.Extra(); ok {
_spec.SetField(account.FieldExtra, field.TypeJSON, value)
}
if value, ok := _u.mutation.ProxyID(); ok {
_spec.SetField(account.FieldProxyID, field.TypeInt64, value)
}
if value, ok := _u.mutation.AddedProxyID(); ok {
_spec.AddField(account.FieldProxyID, field.TypeInt64, value)
}
if _u.mutation.ProxyIDCleared() {
_spec.ClearField(account.FieldProxyID, field.TypeInt64)
}
if value, ok := _u.mutation.Concurrency(); ok {
_spec.SetField(account.FieldConcurrency, field.TypeInt, value)
}
......@@ -647,6 +680,80 @@ func (_u *AccountUpdate) sqlSave(ctx context.Context) (_node int, err error) {
edge.Target.Fields = specE.Fields
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.ProxyCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: account.ProxyTable,
Columns: []string{account.ProxyColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.ProxyIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: account.ProxyTable,
Columns: []string{account.ProxyColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.UsageLogsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.UsageLogsTable,
Columns: []string{account.UsageLogsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedUsageLogsIDs(); len(nodes) > 0 && !_u.mutation.UsageLogsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.UsageLogsTable,
Columns: []string{account.UsageLogsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UsageLogsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.UsageLogsTable,
Columns: []string{account.UsageLogsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{account.Label}
......@@ -749,7 +856,6 @@ func (_u *AccountUpdateOne) SetExtra(v map[string]interface{}) *AccountUpdateOne
// SetProxyID sets the "proxy_id" field.
func (_u *AccountUpdateOne) SetProxyID(v int64) *AccountUpdateOne {
_u.mutation.ResetProxyID()
_u.mutation.SetProxyID(v)
return _u
}
......@@ -762,12 +868,6 @@ func (_u *AccountUpdateOne) SetNillableProxyID(v *int64) *AccountUpdateOne {
return _u
}
// AddProxyID adds value to the "proxy_id" field.
func (_u *AccountUpdateOne) AddProxyID(v int64) *AccountUpdateOne {
_u.mutation.AddProxyID(v)
return _u
}
// ClearProxyID clears the value of the "proxy_id" field.
func (_u *AccountUpdateOne) ClearProxyID() *AccountUpdateOne {
_u.mutation.ClearProxyID()
......@@ -1019,6 +1119,26 @@ func (_u *AccountUpdateOne) AddGroups(v ...*Group) *AccountUpdateOne {
return _u.AddGroupIDs(ids...)
}
// SetProxy sets the "proxy" edge to the Proxy entity.
func (_u *AccountUpdateOne) SetProxy(v *Proxy) *AccountUpdateOne {
return _u.SetProxyID(v.ID)
}
// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by IDs.
func (_u *AccountUpdateOne) AddUsageLogIDs(ids ...int64) *AccountUpdateOne {
_u.mutation.AddUsageLogIDs(ids...)
return _u
}
// AddUsageLogs adds the "usage_logs" edges to the UsageLog entity.
func (_u *AccountUpdateOne) AddUsageLogs(v ...*UsageLog) *AccountUpdateOne {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddUsageLogIDs(ids...)
}
// Mutation returns the AccountMutation object of the builder.
func (_u *AccountUpdateOne) Mutation() *AccountMutation {
return _u.mutation
......@@ -1045,6 +1165,33 @@ func (_u *AccountUpdateOne) RemoveGroups(v ...*Group) *AccountUpdateOne {
return _u.RemoveGroupIDs(ids...)
}
// ClearProxy clears the "proxy" edge to the Proxy entity.
func (_u *AccountUpdateOne) ClearProxy() *AccountUpdateOne {
_u.mutation.ClearProxy()
return _u
}
// ClearUsageLogs clears all "usage_logs" edges to the UsageLog entity.
func (_u *AccountUpdateOne) ClearUsageLogs() *AccountUpdateOne {
_u.mutation.ClearUsageLogs()
return _u
}
// RemoveUsageLogIDs removes the "usage_logs" edge to UsageLog entities by IDs.
func (_u *AccountUpdateOne) RemoveUsageLogIDs(ids ...int64) *AccountUpdateOne {
_u.mutation.RemoveUsageLogIDs(ids...)
return _u
}
// RemoveUsageLogs removes "usage_logs" edges to UsageLog entities.
func (_u *AccountUpdateOne) RemoveUsageLogs(v ...*UsageLog) *AccountUpdateOne {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveUsageLogIDs(ids...)
}
// Where appends a list predicates to the AccountUpdate builder.
func (_u *AccountUpdateOne) Where(ps ...predicate.Account) *AccountUpdateOne {
_u.mutation.Where(ps...)
......@@ -1183,15 +1330,6 @@ func (_u *AccountUpdateOne) sqlSave(ctx context.Context) (_node *Account, err er
if value, ok := _u.mutation.Extra(); ok {
_spec.SetField(account.FieldExtra, field.TypeJSON, value)
}
if value, ok := _u.mutation.ProxyID(); ok {
_spec.SetField(account.FieldProxyID, field.TypeInt64, value)
}
if value, ok := _u.mutation.AddedProxyID(); ok {
_spec.AddField(account.FieldProxyID, field.TypeInt64, value)
}
if _u.mutation.ProxyIDCleared() {
_spec.ClearField(account.FieldProxyID, field.TypeInt64)
}
if value, ok := _u.mutation.Concurrency(); ok {
_spec.SetField(account.FieldConcurrency, field.TypeInt, value)
}
......@@ -1315,6 +1453,80 @@ func (_u *AccountUpdateOne) sqlSave(ctx context.Context) (_node *Account, err er
edge.Target.Fields = specE.Fields
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.ProxyCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: account.ProxyTable,
Columns: []string{account.ProxyColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.ProxyIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: account.ProxyTable,
Columns: []string{account.ProxyColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(proxy.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.UsageLogsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.UsageLogsTable,
Columns: []string{account.UsageLogsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedUsageLogsIDs(); len(nodes) > 0 && !_u.mutation.UsageLogsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.UsageLogsTable,
Columns: []string{account.UsageLogsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UsageLogsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: account.UsageLogsTable,
Columns: []string{account.UsageLogsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Account{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
......
......@@ -47,9 +47,11 @@ type ApiKeyEdges struct {
User *User `json:"user,omitempty"`
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// UsageLogs holds the value of the usage_logs edge.
UsageLogs []*UsageLog `json:"usage_logs,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
loadedTypes [3]bool
}
// UserOrErr returns the User value or an error if the edge
......@@ -74,6 +76,15 @@ func (e ApiKeyEdges) GroupOrErr() (*Group, error) {
return nil, &NotLoadedError{edge: "group"}
}
// UsageLogsOrErr returns the UsageLogs value or an error if the edge
// was not loaded in eager-loading.
func (e ApiKeyEdges) UsageLogsOrErr() ([]*UsageLog, error) {
if e.loadedTypes[2] {
return e.UsageLogs, nil
}
return nil, &NotLoadedError{edge: "usage_logs"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*ApiKey) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
......@@ -179,6 +190,11 @@ func (_m *ApiKey) QueryGroup() *GroupQuery {
return NewApiKeyClient(_m.config).QueryGroup(_m)
}
// QueryUsageLogs queries the "usage_logs" edge of the ApiKey entity.
func (_m *ApiKey) QueryUsageLogs() *UsageLogQuery {
return NewApiKeyClient(_m.config).QueryUsageLogs(_m)
}
// Update returns a builder for updating this ApiKey.
// Note that you need to call ApiKey.Unwrap() before calling this method if this ApiKey
// was returned from a transaction, and the transaction was committed or rolled back.
......
......@@ -35,6 +35,8 @@ const (
EdgeUser = "user"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// EdgeUsageLogs holds the string denoting the usage_logs edge name in mutations.
EdgeUsageLogs = "usage_logs"
// Table holds the table name of the apikey in the database.
Table = "api_keys"
// UserTable is the table that holds the user relation/edge.
......@@ -51,6 +53,13 @@ const (
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "group_id"
// UsageLogsTable is the table that holds the usage_logs relation/edge.
UsageLogsTable = "usage_logs"
// UsageLogsInverseTable is the table name for the UsageLog entity.
// It exists in this package in order to avoid circular dependency with the "usagelog" package.
UsageLogsInverseTable = "usage_logs"
// UsageLogsColumn is the table column denoting the usage_logs relation/edge.
UsageLogsColumn = "api_key_id"
)
// Columns holds all SQL columns for apikey fields.
......@@ -161,6 +170,20 @@ func ByGroupField(field string, opts ...sql.OrderTermOption) OrderOption {
sqlgraph.OrderByNeighborTerms(s, newGroupStep(), sql.OrderByField(field, opts...))
}
}
// ByUsageLogsCount orders the results by usage_logs count.
func ByUsageLogsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newUsageLogsStep(), opts...)
}
}
// ByUsageLogs orders the results by usage_logs terms.
func ByUsageLogs(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUsageLogsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newUserStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
......@@ -175,3 +198,10 @@ func newGroupStep() *sqlgraph.Step {
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
}
func newUsageLogsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UsageLogsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, UsageLogsTable, UsageLogsColumn),
)
}
......@@ -516,6 +516,29 @@ func HasGroupWith(preds ...predicate.Group) predicate.ApiKey {
})
}
// HasUsageLogs applies the HasEdge predicate on the "usage_logs" edge.
func HasUsageLogs() predicate.ApiKey {
return predicate.ApiKey(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, UsageLogsTable, UsageLogsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasUsageLogsWith applies the HasEdge predicate on the "usage_logs" edge with a given conditions (other predicates).
func HasUsageLogsWith(preds ...predicate.UsageLog) predicate.ApiKey {
return predicate.ApiKey(func(s *sql.Selector) {
step := newUsageLogsStep()
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.ApiKey) predicate.ApiKey {
return predicate.ApiKey(sql.AndPredicates(predicates...))
......
......@@ -13,6 +13,7 @@ import (
"entgo.io/ent/schema/field"
"github.com/Wei-Shaw/sub2api/ent/apikey"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user"
)
......@@ -122,6 +123,21 @@ func (_c *ApiKeyCreate) SetGroup(v *Group) *ApiKeyCreate {
return _c.SetGroupID(v.ID)
}
// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by IDs.
func (_c *ApiKeyCreate) AddUsageLogIDs(ids ...int64) *ApiKeyCreate {
_c.mutation.AddUsageLogIDs(ids...)
return _c
}
// AddUsageLogs adds the "usage_logs" edges to the UsageLog entity.
func (_c *ApiKeyCreate) AddUsageLogs(v ...*UsageLog) *ApiKeyCreate {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddUsageLogIDs(ids...)
}
// Mutation returns the ApiKeyMutation object of the builder.
func (_c *ApiKeyCreate) Mutation() *ApiKeyMutation {
return _c.mutation
......@@ -303,6 +319,22 @@ func (_c *ApiKeyCreate) createSpec() (*ApiKey, *sqlgraph.CreateSpec) {
_node.GroupID = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.UsageLogsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: apikey.UsageLogsTable,
Columns: []string{apikey.UsageLogsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
......
......@@ -4,6 +4,7 @@ package ent
import (
"context"
"database/sql/driver"
"fmt"
"math"
......@@ -14,6 +15,7 @@ import (
"github.com/Wei-Shaw/sub2api/ent/apikey"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
"github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user"
)
......@@ -26,6 +28,7 @@ type ApiKeyQuery struct {
predicates []predicate.ApiKey
withUser *UserQuery
withGroup *GroupQuery
withUsageLogs *UsageLogQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
......@@ -106,6 +109,28 @@ func (_q *ApiKeyQuery) QueryGroup() *GroupQuery {
return query
}
// QueryUsageLogs chains the current query on the "usage_logs" edge.
func (_q *ApiKeyQuery) QueryUsageLogs() *UsageLogQuery {
query := (&UsageLogClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(apikey.Table, apikey.FieldID, selector),
sqlgraph.To(usagelog.Table, usagelog.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, apikey.UsageLogsTable, apikey.UsageLogsColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first ApiKey entity from the query.
// Returns a *NotFoundError when no ApiKey was found.
func (_q *ApiKeyQuery) First(ctx context.Context) (*ApiKey, error) {
......@@ -300,6 +325,7 @@ func (_q *ApiKeyQuery) Clone() *ApiKeyQuery {
predicates: append([]predicate.ApiKey{}, _q.predicates...),
withUser: _q.withUser.Clone(),
withGroup: _q.withGroup.Clone(),
withUsageLogs: _q.withUsageLogs.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
......@@ -328,6 +354,17 @@ func (_q *ApiKeyQuery) WithGroup(opts ...func(*GroupQuery)) *ApiKeyQuery {
return _q
}
// WithUsageLogs tells the query-builder to eager-load the nodes that are connected to
// the "usage_logs" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *ApiKeyQuery) WithUsageLogs(opts ...func(*UsageLogQuery)) *ApiKeyQuery {
query := (&UsageLogClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withUsageLogs = query
return _q
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
......@@ -406,9 +443,10 @@ func (_q *ApiKeyQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ApiKe
var (
nodes = []*ApiKey{}
_spec = _q.querySpec()
loadedTypes = [2]bool{
loadedTypes = [3]bool{
_q.withUser != nil,
_q.withGroup != nil,
_q.withUsageLogs != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
......@@ -441,6 +479,13 @@ func (_q *ApiKeyQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ApiKe
return nil, err
}
}
if query := _q.withUsageLogs; query != nil {
if err := _q.loadUsageLogs(ctx, query, nodes,
func(n *ApiKey) { n.Edges.UsageLogs = []*UsageLog{} },
func(n *ApiKey, e *UsageLog) { n.Edges.UsageLogs = append(n.Edges.UsageLogs, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
......@@ -505,6 +550,36 @@ func (_q *ApiKeyQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes [
}
return nil
}
func (_q *ApiKeyQuery) loadUsageLogs(ctx context.Context, query *UsageLogQuery, nodes []*ApiKey, init func(*ApiKey), assign func(*ApiKey, *UsageLog)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[int64]*ApiKey)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
if len(query.ctx.Fields) > 0 {
query.ctx.AppendFieldOnce(usagelog.FieldAPIKeyID)
}
query.Where(predicate.UsageLog(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(apikey.UsageLogsColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.APIKeyID
node, ok := nodeids[fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "api_key_id" returned %v for node %v`, fk, n.ID)
}
assign(node, n)
}
return nil
}
func (_q *ApiKeyQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
......
......@@ -14,6 +14,7 @@ import (
"github.com/Wei-Shaw/sub2api/ent/apikey"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
"github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user"
)
......@@ -142,6 +143,21 @@ func (_u *ApiKeyUpdate) SetGroup(v *Group) *ApiKeyUpdate {
return _u.SetGroupID(v.ID)
}
// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by IDs.
func (_u *ApiKeyUpdate) AddUsageLogIDs(ids ...int64) *ApiKeyUpdate {
_u.mutation.AddUsageLogIDs(ids...)
return _u
}
// AddUsageLogs adds the "usage_logs" edges to the UsageLog entity.
func (_u *ApiKeyUpdate) AddUsageLogs(v ...*UsageLog) *ApiKeyUpdate {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddUsageLogIDs(ids...)
}
// Mutation returns the ApiKeyMutation object of the builder.
func (_u *ApiKeyUpdate) Mutation() *ApiKeyMutation {
return _u.mutation
......@@ -159,6 +175,27 @@ func (_u *ApiKeyUpdate) ClearGroup() *ApiKeyUpdate {
return _u
}
// ClearUsageLogs clears all "usage_logs" edges to the UsageLog entity.
func (_u *ApiKeyUpdate) ClearUsageLogs() *ApiKeyUpdate {
_u.mutation.ClearUsageLogs()
return _u
}
// RemoveUsageLogIDs removes the "usage_logs" edge to UsageLog entities by IDs.
func (_u *ApiKeyUpdate) RemoveUsageLogIDs(ids ...int64) *ApiKeyUpdate {
_u.mutation.RemoveUsageLogIDs(ids...)
return _u
}
// RemoveUsageLogs removes "usage_logs" edges to UsageLog entities.
func (_u *ApiKeyUpdate) RemoveUsageLogs(v ...*UsageLog) *ApiKeyUpdate {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveUsageLogIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *ApiKeyUpdate) Save(ctx context.Context) (int, error) {
if err := _u.defaults(); err != nil {
......@@ -312,6 +349,51 @@ func (_u *ApiKeyUpdate) sqlSave(ctx context.Context) (_node int, err error) {
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.UsageLogsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: apikey.UsageLogsTable,
Columns: []string{apikey.UsageLogsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedUsageLogsIDs(); len(nodes) > 0 && !_u.mutation.UsageLogsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: apikey.UsageLogsTable,
Columns: []string{apikey.UsageLogsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UsageLogsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: apikey.UsageLogsTable,
Columns: []string{apikey.UsageLogsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{apikey.Label}
......@@ -444,6 +526,21 @@ func (_u *ApiKeyUpdateOne) SetGroup(v *Group) *ApiKeyUpdateOne {
return _u.SetGroupID(v.ID)
}
// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by IDs.
func (_u *ApiKeyUpdateOne) AddUsageLogIDs(ids ...int64) *ApiKeyUpdateOne {
_u.mutation.AddUsageLogIDs(ids...)
return _u
}
// AddUsageLogs adds the "usage_logs" edges to the UsageLog entity.
func (_u *ApiKeyUpdateOne) AddUsageLogs(v ...*UsageLog) *ApiKeyUpdateOne {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddUsageLogIDs(ids...)
}
// Mutation returns the ApiKeyMutation object of the builder.
func (_u *ApiKeyUpdateOne) Mutation() *ApiKeyMutation {
return _u.mutation
......@@ -461,6 +558,27 @@ func (_u *ApiKeyUpdateOne) ClearGroup() *ApiKeyUpdateOne {
return _u
}
// ClearUsageLogs clears all "usage_logs" edges to the UsageLog entity.
func (_u *ApiKeyUpdateOne) ClearUsageLogs() *ApiKeyUpdateOne {
_u.mutation.ClearUsageLogs()
return _u
}
// RemoveUsageLogIDs removes the "usage_logs" edge to UsageLog entities by IDs.
func (_u *ApiKeyUpdateOne) RemoveUsageLogIDs(ids ...int64) *ApiKeyUpdateOne {
_u.mutation.RemoveUsageLogIDs(ids...)
return _u
}
// RemoveUsageLogs removes "usage_logs" edges to UsageLog entities.
func (_u *ApiKeyUpdateOne) RemoveUsageLogs(v ...*UsageLog) *ApiKeyUpdateOne {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveUsageLogIDs(ids...)
}
// Where appends a list predicates to the ApiKeyUpdate builder.
func (_u *ApiKeyUpdateOne) Where(ps ...predicate.ApiKey) *ApiKeyUpdateOne {
_u.mutation.Where(ps...)
......@@ -644,6 +762,51 @@ func (_u *ApiKeyUpdateOne) sqlSave(ctx context.Context) (_node *ApiKey, err erro
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.UsageLogsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: apikey.UsageLogsTable,
Columns: []string{apikey.UsageLogsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedUsageLogsIDs(); len(nodes) > 0 && !_u.mutation.UsageLogsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: apikey.UsageLogsTable,
Columns: []string{apikey.UsageLogsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.UsageLogsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: apikey.UsageLogsTable,
Columns: []string{apikey.UsageLogsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &ApiKey{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
......
......@@ -22,6 +22,7 @@ import (
"github.com/Wei-Shaw/sub2api/ent/proxy"
"github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/setting"
"github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
"github.com/Wei-Shaw/sub2api/ent/usersubscription"
......@@ -48,6 +49,8 @@ type Client struct {
RedeemCode *RedeemCodeClient
// Setting is the client for interacting with the Setting builders.
Setting *SettingClient
// UsageLog is the client for interacting with the UsageLog builders.
UsageLog *UsageLogClient
// User is the client for interacting with the User builders.
User *UserClient
// UserAllowedGroup is the client for interacting with the UserAllowedGroup builders.
......@@ -72,6 +75,7 @@ func (c *Client) init() {
c.Proxy = NewProxyClient(c.config)
c.RedeemCode = NewRedeemCodeClient(c.config)
c.Setting = NewSettingClient(c.config)
c.UsageLog = NewUsageLogClient(c.config)
c.User = NewUserClient(c.config)
c.UserAllowedGroup = NewUserAllowedGroupClient(c.config)
c.UserSubscription = NewUserSubscriptionClient(c.config)
......@@ -174,6 +178,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
Proxy: NewProxyClient(cfg),
RedeemCode: NewRedeemCodeClient(cfg),
Setting: NewSettingClient(cfg),
UsageLog: NewUsageLogClient(cfg),
User: NewUserClient(cfg),
UserAllowedGroup: NewUserAllowedGroupClient(cfg),
UserSubscription: NewUserSubscriptionClient(cfg),
......@@ -203,6 +208,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
Proxy: NewProxyClient(cfg),
RedeemCode: NewRedeemCodeClient(cfg),
Setting: NewSettingClient(cfg),
UsageLog: NewUsageLogClient(cfg),
User: NewUserClient(cfg),
UserAllowedGroup: NewUserAllowedGroupClient(cfg),
UserSubscription: NewUserSubscriptionClient(cfg),
......@@ -236,7 +242,7 @@ func (c *Client) Close() error {
func (c *Client) Use(hooks ...Hook) {
for _, n := range []interface{ Use(...Hook) }{
c.Account, c.AccountGroup, c.ApiKey, c.Group, c.Proxy, c.RedeemCode, c.Setting,
c.User, c.UserAllowedGroup, c.UserSubscription,
c.UsageLog, c.User, c.UserAllowedGroup, c.UserSubscription,
} {
n.Use(hooks...)
}
......@@ -247,7 +253,7 @@ func (c *Client) Use(hooks ...Hook) {
func (c *Client) Intercept(interceptors ...Interceptor) {
for _, n := range []interface{ Intercept(...Interceptor) }{
c.Account, c.AccountGroup, c.ApiKey, c.Group, c.Proxy, c.RedeemCode, c.Setting,
c.User, c.UserAllowedGroup, c.UserSubscription,
c.UsageLog, c.User, c.UserAllowedGroup, c.UserSubscription,
} {
n.Intercept(interceptors...)
}
......@@ -270,6 +276,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
return c.RedeemCode.mutate(ctx, m)
case *SettingMutation:
return c.Setting.mutate(ctx, m)
case *UsageLogMutation:
return c.UsageLog.mutate(ctx, m)
case *UserMutation:
return c.User.mutate(ctx, m)
case *UserAllowedGroupMutation:
......@@ -405,6 +413,38 @@ func (c *AccountClient) QueryGroups(_m *Account) *GroupQuery {
return query
}
// QueryProxy queries the proxy edge of a Account.
func (c *AccountClient) QueryProxy(_m *Account) *ProxyQuery {
query := (&ProxyClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(account.Table, account.FieldID, id),
sqlgraph.To(proxy.Table, proxy.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, account.ProxyTable, account.ProxyColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryUsageLogs queries the usage_logs edge of a Account.
func (c *AccountClient) QueryUsageLogs(_m *Account) *UsageLogQuery {
query := (&UsageLogClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(account.Table, account.FieldID, id),
sqlgraph.To(usagelog.Table, usagelog.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, account.UsageLogsTable, account.UsageLogsColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryAccountGroups queries the account_groups edge of a Account.
func (c *AccountClient) QueryAccountGroups(_m *Account) *AccountGroupQuery {
query := (&AccountGroupClient{config: c.config}).Query()
......@@ -704,6 +744,22 @@ func (c *ApiKeyClient) QueryGroup(_m *ApiKey) *GroupQuery {
return query
}
// QueryUsageLogs queries the usage_logs edge of a ApiKey.
func (c *ApiKeyClient) QueryUsageLogs(_m *ApiKey) *UsageLogQuery {
query := (&UsageLogClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(apikey.Table, apikey.FieldID, id),
sqlgraph.To(usagelog.Table, usagelog.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, apikey.UsageLogsTable, apikey.UsageLogsColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *ApiKeyClient) Hooks() []Hook {
hooks := c.hooks.ApiKey
......@@ -887,6 +943,22 @@ func (c *GroupClient) QuerySubscriptions(_m *Group) *UserSubscriptionQuery {
return query
}
// QueryUsageLogs queries the usage_logs edge of a Group.
func (c *GroupClient) QueryUsageLogs(_m *Group) *UsageLogQuery {
query := (&UsageLogClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, id),
sqlgraph.To(usagelog.Table, usagelog.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.UsageLogsTable, group.UsageLogsColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryAccounts queries the accounts edge of a Group.
func (c *GroupClient) QueryAccounts(_m *Group) *AccountQuery {
query := (&AccountClient{config: c.config}).Query()
......@@ -1086,6 +1158,22 @@ func (c *ProxyClient) GetX(ctx context.Context, id int64) *Proxy {
return obj
}
// QueryAccounts queries the accounts edge of a Proxy.
func (c *ProxyClient) QueryAccounts(_m *Proxy) *AccountQuery {
query := (&AccountClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(proxy.Table, proxy.FieldID, id),
sqlgraph.To(account.Table, account.FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, proxy.AccountsTable, proxy.AccountsColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *ProxyClient) Hooks() []Hook {
hooks := c.hooks.Proxy
......@@ -1411,6 +1499,219 @@ func (c *SettingClient) mutate(ctx context.Context, m *SettingMutation) (Value,
}
}
// UsageLogClient is a client for the UsageLog schema.
type UsageLogClient struct {
config
}
// NewUsageLogClient returns a client for the UsageLog from the given config.
func NewUsageLogClient(c config) *UsageLogClient {
return &UsageLogClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `usagelog.Hooks(f(g(h())))`.
func (c *UsageLogClient) Use(hooks ...Hook) {
c.hooks.UsageLog = append(c.hooks.UsageLog, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `usagelog.Intercept(f(g(h())))`.
func (c *UsageLogClient) Intercept(interceptors ...Interceptor) {
c.inters.UsageLog = append(c.inters.UsageLog, interceptors...)
}
// Create returns a builder for creating a UsageLog entity.
func (c *UsageLogClient) Create() *UsageLogCreate {
mutation := newUsageLogMutation(c.config, OpCreate)
return &UsageLogCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of UsageLog entities.
func (c *UsageLogClient) CreateBulk(builders ...*UsageLogCreate) *UsageLogCreateBulk {
return &UsageLogCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *UsageLogClient) MapCreateBulk(slice any, setFunc func(*UsageLogCreate, int)) *UsageLogCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &UsageLogCreateBulk{err: fmt.Errorf("calling to UsageLogClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*UsageLogCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &UsageLogCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for UsageLog.
func (c *UsageLogClient) Update() *UsageLogUpdate {
mutation := newUsageLogMutation(c.config, OpUpdate)
return &UsageLogUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *UsageLogClient) UpdateOne(_m *UsageLog) *UsageLogUpdateOne {
mutation := newUsageLogMutation(c.config, OpUpdateOne, withUsageLog(_m))
return &UsageLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *UsageLogClient) UpdateOneID(id int64) *UsageLogUpdateOne {
mutation := newUsageLogMutation(c.config, OpUpdateOne, withUsageLogID(id))
return &UsageLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for UsageLog.
func (c *UsageLogClient) Delete() *UsageLogDelete {
mutation := newUsageLogMutation(c.config, OpDelete)
return &UsageLogDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *UsageLogClient) DeleteOne(_m *UsageLog) *UsageLogDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *UsageLogClient) DeleteOneID(id int64) *UsageLogDeleteOne {
builder := c.Delete().Where(usagelog.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &UsageLogDeleteOne{builder}
}
// Query returns a query builder for UsageLog.
func (c *UsageLogClient) Query() *UsageLogQuery {
return &UsageLogQuery{
config: c.config,
ctx: &QueryContext{Type: TypeUsageLog},
inters: c.Interceptors(),
}
}
// Get returns a UsageLog entity by its id.
func (c *UsageLogClient) Get(ctx context.Context, id int64) (*UsageLog, error) {
return c.Query().Where(usagelog.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *UsageLogClient) GetX(ctx context.Context, id int64) *UsageLog {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryUser queries the user edge of a UsageLog.
func (c *UsageLogClient) QueryUser(_m *UsageLog) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(usagelog.Table, usagelog.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, usagelog.UserTable, usagelog.UserColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryAPIKey queries the api_key edge of a UsageLog.
func (c *UsageLogClient) QueryAPIKey(_m *UsageLog) *ApiKeyQuery {
query := (&ApiKeyClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(usagelog.Table, usagelog.FieldID, id),
sqlgraph.To(apikey.Table, apikey.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, usagelog.APIKeyTable, usagelog.APIKeyColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryAccount queries the account edge of a UsageLog.
func (c *UsageLogClient) QueryAccount(_m *UsageLog) *AccountQuery {
query := (&AccountClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(usagelog.Table, usagelog.FieldID, id),
sqlgraph.To(account.Table, account.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, usagelog.AccountTable, usagelog.AccountColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryGroup queries the group edge of a UsageLog.
func (c *UsageLogClient) QueryGroup(_m *UsageLog) *GroupQuery {
query := (&GroupClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(usagelog.Table, usagelog.FieldID, id),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, usagelog.GroupTable, usagelog.GroupColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QuerySubscription queries the subscription edge of a UsageLog.
func (c *UsageLogClient) QuerySubscription(_m *UsageLog) *UserSubscriptionQuery {
query := (&UserSubscriptionClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(usagelog.Table, usagelog.FieldID, id),
sqlgraph.To(usersubscription.Table, usersubscription.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, usagelog.SubscriptionTable, usagelog.SubscriptionColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *UsageLogClient) Hooks() []Hook {
return c.hooks.UsageLog
}
// Interceptors returns the client interceptors.
func (c *UsageLogClient) Interceptors() []Interceptor {
return c.inters.UsageLog
}
func (c *UsageLogClient) mutate(ctx context.Context, m *UsageLogMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&UsageLogCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&UsageLogUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&UsageLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&UsageLogDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown UsageLog mutation op: %q", m.Op())
}
}
// UserClient is a client for the User schema.
type UserClient struct {
config
......@@ -1599,6 +1900,22 @@ func (c *UserClient) QueryAllowedGroups(_m *User) *GroupQuery {
return query
}
// QueryUsageLogs queries the usage_logs edge of a User.
func (c *UserClient) QueryUsageLogs(_m *User) *UsageLogQuery {
query := (&UsageLogClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(usagelog.Table, usagelog.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, user.UsageLogsTable, user.UsageLogsColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryUserAllowedGroups queries the user_allowed_groups edge of a User.
func (c *UserClient) QueryUserAllowedGroups(_m *User) *UserAllowedGroupQuery {
query := (&UserAllowedGroupClient{config: c.config}).Query()
......@@ -1914,14 +2231,32 @@ func (c *UserSubscriptionClient) QueryAssignedByUser(_m *UserSubscription) *User
return query
}
// QueryUsageLogs queries the usage_logs edge of a UserSubscription.
func (c *UserSubscriptionClient) QueryUsageLogs(_m *UserSubscription) *UsageLogQuery {
query := (&UsageLogClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(usersubscription.Table, usersubscription.FieldID, id),
sqlgraph.To(usagelog.Table, usagelog.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, usersubscription.UsageLogsTable, usersubscription.UsageLogsColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *UserSubscriptionClient) Hooks() []Hook {
return c.hooks.UserSubscription
hooks := c.hooks.UserSubscription
return append(hooks[:len(hooks):len(hooks)], usersubscription.Hooks[:]...)
}
// Interceptors returns the client interceptors.
func (c *UserSubscriptionClient) Interceptors() []Interceptor {
return c.inters.UserSubscription
inters := c.inters.UserSubscription
return append(inters[:len(inters):len(inters)], usersubscription.Interceptors[:]...)
}
func (c *UserSubscriptionClient) mutate(ctx context.Context, m *UserSubscriptionMutation) (Value, error) {
......@@ -1942,16 +2277,15 @@ func (c *UserSubscriptionClient) mutate(ctx context.Context, m *UserSubscription
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Account, AccountGroup, ApiKey, Group, Proxy, RedeemCode, Setting, User,
UserAllowedGroup, UserSubscription []ent.Hook
Account, AccountGroup, ApiKey, Group, Proxy, RedeemCode, Setting, UsageLog,
User, UserAllowedGroup, UserSubscription []ent.Hook
}
inters struct {
Account, AccountGroup, ApiKey, Group, Proxy, RedeemCode, Setting, User,
UserAllowedGroup, UserSubscription []ent.Interceptor
Account, AccountGroup, ApiKey, Group, Proxy, RedeemCode, Setting, UsageLog,
User, UserAllowedGroup, UserSubscription []ent.Interceptor
}
)
// ExecContext 透传到底层 driver,用于在 ent 事务中执行原生 SQL(例如同步 legacy 字段)。
// ExecContext allows calling the underlying ExecContext method of the driver if it is supported by it.
// See, database/sql#DB.ExecContext for more information.
func (c *config) ExecContext(ctx context.Context, query string, args ...any) (stdsql.Result, error) {
......@@ -1964,7 +2298,6 @@ func (c *config) ExecContext(ctx context.Context, query string, args ...any) (st
return ex.ExecContext(ctx, query, args...)
}
// QueryContext 透传到底层 driver,用于在事务内执行原生查询并共享锁/一致性语义。
// QueryContext allows calling the underlying QueryContext method of the driver if it is supported by it.
// See, database/sql#DB.QueryContext for more information.
func (c *config) QueryContext(ctx context.Context, query string, args ...any) (*stdsql.Rows, error) {
......
......@@ -19,6 +19,7 @@ import (
"github.com/Wei-Shaw/sub2api/ent/proxy"
"github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/setting"
"github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/userallowedgroup"
"github.com/Wei-Shaw/sub2api/ent/usersubscription"
......@@ -89,6 +90,7 @@ func checkColumn(t, c string) error {
proxy.Table: proxy.ValidColumn,
redeemcode.Table: redeemcode.ValidColumn,
setting.Table: setting.ValidColumn,
usagelog.Table: usagelog.ValidColumn,
user.Table: user.ValidColumn,
userallowedgroup.Table: userallowedgroup.ValidColumn,
usersubscription.Table: usersubscription.ValidColumn,
......
......@@ -43,6 +43,8 @@ type Group struct {
WeeklyLimitUsd *float64 `json:"weekly_limit_usd,omitempty"`
// MonthlyLimitUsd holds the value of the "monthly_limit_usd" field.
MonthlyLimitUsd *float64 `json:"monthly_limit_usd,omitempty"`
// DefaultValidityDays holds the value of the "default_validity_days" field.
DefaultValidityDays int `json:"default_validity_days,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the GroupQuery when eager-loading is set.
Edges GroupEdges `json:"edges"`
......@@ -57,6 +59,8 @@ type GroupEdges struct {
RedeemCodes []*RedeemCode `json:"redeem_codes,omitempty"`
// Subscriptions holds the value of the subscriptions edge.
Subscriptions []*UserSubscription `json:"subscriptions,omitempty"`
// UsageLogs holds the value of the usage_logs edge.
UsageLogs []*UsageLog `json:"usage_logs,omitempty"`
// Accounts holds the value of the accounts edge.
Accounts []*Account `json:"accounts,omitempty"`
// AllowedUsers holds the value of the allowed_users edge.
......@@ -67,7 +71,7 @@ type GroupEdges struct {
UserAllowedGroups []*UserAllowedGroup `json:"user_allowed_groups,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [7]bool
loadedTypes [8]bool
}
// APIKeysOrErr returns the APIKeys value or an error if the edge
......@@ -97,10 +101,19 @@ func (e GroupEdges) SubscriptionsOrErr() ([]*UserSubscription, error) {
return nil, &NotLoadedError{edge: "subscriptions"}
}
// UsageLogsOrErr returns the UsageLogs value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) UsageLogsOrErr() ([]*UsageLog, error) {
if e.loadedTypes[3] {
return e.UsageLogs, nil
}
return nil, &NotLoadedError{edge: "usage_logs"}
}
// AccountsOrErr returns the Accounts value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) AccountsOrErr() ([]*Account, error) {
if e.loadedTypes[3] {
if e.loadedTypes[4] {
return e.Accounts, nil
}
return nil, &NotLoadedError{edge: "accounts"}
......@@ -109,7 +122,7 @@ func (e GroupEdges) AccountsOrErr() ([]*Account, error) {
// AllowedUsersOrErr returns the AllowedUsers value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) AllowedUsersOrErr() ([]*User, error) {
if e.loadedTypes[4] {
if e.loadedTypes[5] {
return e.AllowedUsers, nil
}
return nil, &NotLoadedError{edge: "allowed_users"}
......@@ -118,7 +131,7 @@ func (e GroupEdges) AllowedUsersOrErr() ([]*User, error) {
// AccountGroupsOrErr returns the AccountGroups value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) AccountGroupsOrErr() ([]*AccountGroup, error) {
if e.loadedTypes[5] {
if e.loadedTypes[6] {
return e.AccountGroups, nil
}
return nil, &NotLoadedError{edge: "account_groups"}
......@@ -127,7 +140,7 @@ func (e GroupEdges) AccountGroupsOrErr() ([]*AccountGroup, error) {
// UserAllowedGroupsOrErr returns the UserAllowedGroups value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) UserAllowedGroupsOrErr() ([]*UserAllowedGroup, error) {
if e.loadedTypes[6] {
if e.loadedTypes[7] {
return e.UserAllowedGroups, nil
}
return nil, &NotLoadedError{edge: "user_allowed_groups"}
......@@ -142,7 +155,7 @@ func (*Group) scanValues(columns []string) ([]any, error) {
values[i] = new(sql.NullBool)
case group.FieldRateMultiplier, group.FieldDailyLimitUsd, group.FieldWeeklyLimitUsd, group.FieldMonthlyLimitUsd:
values[i] = new(sql.NullFloat64)
case group.FieldID:
case group.FieldID, group.FieldDefaultValidityDays:
values[i] = new(sql.NullInt64)
case group.FieldName, group.FieldDescription, group.FieldStatus, group.FieldPlatform, group.FieldSubscriptionType:
values[i] = new(sql.NullString)
......@@ -252,6 +265,12 @@ func (_m *Group) assignValues(columns []string, values []any) error {
_m.MonthlyLimitUsd = new(float64)
*_m.MonthlyLimitUsd = value.Float64
}
case group.FieldDefaultValidityDays:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field default_validity_days", values[i])
} else if value.Valid {
_m.DefaultValidityDays = int(value.Int64)
}
default:
_m.selectValues.Set(columns[i], values[i])
}
......@@ -280,6 +299,11 @@ func (_m *Group) QuerySubscriptions() *UserSubscriptionQuery {
return NewGroupClient(_m.config).QuerySubscriptions(_m)
}
// QueryUsageLogs queries the "usage_logs" edge of the Group entity.
func (_m *Group) QueryUsageLogs() *UsageLogQuery {
return NewGroupClient(_m.config).QueryUsageLogs(_m)
}
// QueryAccounts queries the "accounts" edge of the Group entity.
func (_m *Group) QueryAccounts() *AccountQuery {
return NewGroupClient(_m.config).QueryAccounts(_m)
......@@ -371,6 +395,9 @@ func (_m *Group) String() string {
builder.WriteString("monthly_limit_usd=")
builder.WriteString(fmt.Sprintf("%v", *v))
}
builder.WriteString(", ")
builder.WriteString("default_validity_days=")
builder.WriteString(fmt.Sprintf("%v", _m.DefaultValidityDays))
builder.WriteByte(')')
return builder.String()
}
......
......@@ -41,12 +41,16 @@ const (
FieldWeeklyLimitUsd = "weekly_limit_usd"
// FieldMonthlyLimitUsd holds the string denoting the monthly_limit_usd field in the database.
FieldMonthlyLimitUsd = "monthly_limit_usd"
// FieldDefaultValidityDays holds the string denoting the default_validity_days field in the database.
FieldDefaultValidityDays = "default_validity_days"
// EdgeAPIKeys holds the string denoting the api_keys edge name in mutations.
EdgeAPIKeys = "api_keys"
// EdgeRedeemCodes holds the string denoting the redeem_codes edge name in mutations.
EdgeRedeemCodes = "redeem_codes"
// EdgeSubscriptions holds the string denoting the subscriptions edge name in mutations.
EdgeSubscriptions = "subscriptions"
// EdgeUsageLogs holds the string denoting the usage_logs edge name in mutations.
EdgeUsageLogs = "usage_logs"
// EdgeAccounts holds the string denoting the accounts edge name in mutations.
EdgeAccounts = "accounts"
// EdgeAllowedUsers holds the string denoting the allowed_users edge name in mutations.
......@@ -78,6 +82,13 @@ const (
SubscriptionsInverseTable = "user_subscriptions"
// SubscriptionsColumn is the table column denoting the subscriptions relation/edge.
SubscriptionsColumn = "group_id"
// UsageLogsTable is the table that holds the usage_logs relation/edge.
UsageLogsTable = "usage_logs"
// UsageLogsInverseTable is the table name for the UsageLog entity.
// It exists in this package in order to avoid circular dependency with the "usagelog" package.
UsageLogsInverseTable = "usage_logs"
// UsageLogsColumn is the table column denoting the usage_logs relation/edge.
UsageLogsColumn = "group_id"
// AccountsTable is the table that holds the accounts relation/edge. The primary key declared below.
AccountsTable = "account_groups"
// AccountsInverseTable is the table name for the Account entity.
......@@ -120,6 +131,7 @@ var Columns = []string{
FieldDailyLimitUsd,
FieldWeeklyLimitUsd,
FieldMonthlyLimitUsd,
FieldDefaultValidityDays,
}
var (
......@@ -173,6 +185,8 @@ var (
DefaultSubscriptionType string
// SubscriptionTypeValidator is a validator for the "subscription_type" field. It is called by the builders before save.
SubscriptionTypeValidator func(string) error
// DefaultDefaultValidityDays holds the default value on creation for the "default_validity_days" field.
DefaultDefaultValidityDays int
)
// OrderOption defines the ordering options for the Group queries.
......@@ -248,6 +262,11 @@ func ByMonthlyLimitUsd(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldMonthlyLimitUsd, opts...).ToFunc()
}
// ByDefaultValidityDays orders the results by the default_validity_days field.
func ByDefaultValidityDays(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDefaultValidityDays, opts...).ToFunc()
}
// ByAPIKeysCount orders the results by api_keys count.
func ByAPIKeysCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
......@@ -290,6 +309,20 @@ func BySubscriptions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
}
}
// ByUsageLogsCount orders the results by usage_logs count.
func ByUsageLogsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newUsageLogsStep(), opts...)
}
}
// ByUsageLogs orders the results by usage_logs terms.
func ByUsageLogs(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newUsageLogsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByAccountsCount orders the results by accounts count.
func ByAccountsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
......@@ -366,6 +399,13 @@ func newSubscriptionsStep() *sqlgraph.Step {
sqlgraph.Edge(sqlgraph.O2M, false, SubscriptionsTable, SubscriptionsColumn),
)
}
func newUsageLogsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UsageLogsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, UsageLogsTable, UsageLogsColumn),
)
}
func newAccountsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
......
......@@ -120,6 +120,11 @@ func MonthlyLimitUsd(v float64) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldMonthlyLimitUsd, v))
}
// DefaultValidityDays applies equality check predicate on the "default_validity_days" field. It's identical to DefaultValidityDaysEQ.
func DefaultValidityDays(v int) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldDefaultValidityDays, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldCreatedAt, v))
......@@ -785,6 +790,46 @@ func MonthlyLimitUsdNotNil() predicate.Group {
return predicate.Group(sql.FieldNotNull(FieldMonthlyLimitUsd))
}
// DefaultValidityDaysEQ applies the EQ predicate on the "default_validity_days" field.
func DefaultValidityDaysEQ(v int) predicate.Group {
return predicate.Group(sql.FieldEQ(FieldDefaultValidityDays, v))
}
// DefaultValidityDaysNEQ applies the NEQ predicate on the "default_validity_days" field.
func DefaultValidityDaysNEQ(v int) predicate.Group {
return predicate.Group(sql.FieldNEQ(FieldDefaultValidityDays, v))
}
// DefaultValidityDaysIn applies the In predicate on the "default_validity_days" field.
func DefaultValidityDaysIn(vs ...int) predicate.Group {
return predicate.Group(sql.FieldIn(FieldDefaultValidityDays, vs...))
}
// DefaultValidityDaysNotIn applies the NotIn predicate on the "default_validity_days" field.
func DefaultValidityDaysNotIn(vs ...int) predicate.Group {
return predicate.Group(sql.FieldNotIn(FieldDefaultValidityDays, vs...))
}
// DefaultValidityDaysGT applies the GT predicate on the "default_validity_days" field.
func DefaultValidityDaysGT(v int) predicate.Group {
return predicate.Group(sql.FieldGT(FieldDefaultValidityDays, v))
}
// DefaultValidityDaysGTE applies the GTE predicate on the "default_validity_days" field.
func DefaultValidityDaysGTE(v int) predicate.Group {
return predicate.Group(sql.FieldGTE(FieldDefaultValidityDays, v))
}
// DefaultValidityDaysLT applies the LT predicate on the "default_validity_days" field.
func DefaultValidityDaysLT(v int) predicate.Group {
return predicate.Group(sql.FieldLT(FieldDefaultValidityDays, v))
}
// DefaultValidityDaysLTE applies the LTE predicate on the "default_validity_days" field.
func DefaultValidityDaysLTE(v int) predicate.Group {
return predicate.Group(sql.FieldLTE(FieldDefaultValidityDays, v))
}
// HasAPIKeys applies the HasEdge predicate on the "api_keys" edge.
func HasAPIKeys() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
......@@ -854,6 +899,29 @@ func HasSubscriptionsWith(preds ...predicate.UserSubscription) predicate.Group {
})
}
// HasUsageLogs applies the HasEdge predicate on the "usage_logs" edge.
func HasUsageLogs() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, UsageLogsTable, UsageLogsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasUsageLogsWith applies the HasEdge predicate on the "usage_logs" edge with a given conditions (other predicates).
func HasUsageLogsWith(preds ...predicate.UsageLog) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := newUsageLogsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasAccounts applies the HasEdge predicate on the "accounts" edge.
func HasAccounts() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
......
......@@ -15,6 +15,7 @@ import (
"github.com/Wei-Shaw/sub2api/ent/apikey"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/redeemcode"
"github.com/Wei-Shaw/sub2api/ent/usagelog"
"github.com/Wei-Shaw/sub2api/ent/user"
"github.com/Wei-Shaw/sub2api/ent/usersubscription"
)
......@@ -201,6 +202,20 @@ func (_c *GroupCreate) SetNillableMonthlyLimitUsd(v *float64) *GroupCreate {
return _c
}
// SetDefaultValidityDays sets the "default_validity_days" field.
func (_c *GroupCreate) SetDefaultValidityDays(v int) *GroupCreate {
_c.mutation.SetDefaultValidityDays(v)
return _c
}
// SetNillableDefaultValidityDays sets the "default_validity_days" field if the given value is not nil.
func (_c *GroupCreate) SetNillableDefaultValidityDays(v *int) *GroupCreate {
if v != nil {
_c.SetDefaultValidityDays(*v)
}
return _c
}
// AddAPIKeyIDs adds the "api_keys" edge to the ApiKey entity by IDs.
func (_c *GroupCreate) AddAPIKeyIDs(ids ...int64) *GroupCreate {
_c.mutation.AddAPIKeyIDs(ids...)
......@@ -246,6 +261,21 @@ func (_c *GroupCreate) AddSubscriptions(v ...*UserSubscription) *GroupCreate {
return _c.AddSubscriptionIDs(ids...)
}
// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by IDs.
func (_c *GroupCreate) AddUsageLogIDs(ids ...int64) *GroupCreate {
_c.mutation.AddUsageLogIDs(ids...)
return _c
}
// AddUsageLogs adds the "usage_logs" edges to the UsageLog entity.
func (_c *GroupCreate) AddUsageLogs(v ...*UsageLog) *GroupCreate {
ids := make([]int64, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddUsageLogIDs(ids...)
}
// AddAccountIDs adds the "accounts" edge to the Account entity by IDs.
func (_c *GroupCreate) AddAccountIDs(ids ...int64) *GroupCreate {
_c.mutation.AddAccountIDs(ids...)
......@@ -347,6 +377,10 @@ func (_c *GroupCreate) defaults() error {
v := group.DefaultSubscriptionType
_c.mutation.SetSubscriptionType(v)
}
if _, ok := _c.mutation.DefaultValidityDays(); !ok {
v := group.DefaultDefaultValidityDays
_c.mutation.SetDefaultValidityDays(v)
}
return nil
}
......@@ -396,6 +430,9 @@ func (_c *GroupCreate) check() error {
return &ValidationError{Name: "subscription_type", err: fmt.Errorf(`ent: validator failed for field "Group.subscription_type": %w`, err)}
}
}
if _, ok := _c.mutation.DefaultValidityDays(); !ok {
return &ValidationError{Name: "default_validity_days", err: errors.New(`ent: missing required field "Group.default_validity_days"`)}
}
return nil
}
......@@ -475,6 +512,10 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
_spec.SetField(group.FieldMonthlyLimitUsd, field.TypeFloat64, value)
_node.MonthlyLimitUsd = &value
}
if value, ok := _c.mutation.DefaultValidityDays(); ok {
_spec.SetField(group.FieldDefaultValidityDays, field.TypeInt, value)
_node.DefaultValidityDays = value
}
if nodes := _c.mutation.APIKeysIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
......@@ -523,6 +564,22 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.UsageLogsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.UsageLogsTable,
Columns: []string{group.UsageLogsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(usagelog.FieldID, field.TypeInt64),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.AccountsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
......@@ -813,6 +870,24 @@ func (u *GroupUpsert) ClearMonthlyLimitUsd() *GroupUpsert {
return u
}
// SetDefaultValidityDays sets the "default_validity_days" field.
func (u *GroupUpsert) SetDefaultValidityDays(v int) *GroupUpsert {
u.Set(group.FieldDefaultValidityDays, v)
return u
}
// UpdateDefaultValidityDays sets the "default_validity_days" field to the value that was provided on create.
func (u *GroupUpsert) UpdateDefaultValidityDays() *GroupUpsert {
u.SetExcluded(group.FieldDefaultValidityDays)
return u
}
// AddDefaultValidityDays adds v to the "default_validity_days" field.
func (u *GroupUpsert) AddDefaultValidityDays(v int) *GroupUpsert {
u.Add(group.FieldDefaultValidityDays, v)
return u
}
// UpdateNewValues updates the mutable fields using the new values that were set on create.
// Using this option is equivalent to using:
//
......@@ -1089,6 +1164,27 @@ func (u *GroupUpsertOne) ClearMonthlyLimitUsd() *GroupUpsertOne {
})
}
// SetDefaultValidityDays sets the "default_validity_days" field.
func (u *GroupUpsertOne) SetDefaultValidityDays(v int) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.SetDefaultValidityDays(v)
})
}
// AddDefaultValidityDays adds v to the "default_validity_days" field.
func (u *GroupUpsertOne) AddDefaultValidityDays(v int) *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.AddDefaultValidityDays(v)
})
}
// UpdateDefaultValidityDays sets the "default_validity_days" field to the value that was provided on create.
func (u *GroupUpsertOne) UpdateDefaultValidityDays() *GroupUpsertOne {
return u.Update(func(s *GroupUpsert) {
s.UpdateDefaultValidityDays()
})
}
// Exec executes the query.
func (u *GroupUpsertOne) Exec(ctx context.Context) error {
if len(u.create.conflict) == 0 {
......@@ -1531,6 +1627,27 @@ func (u *GroupUpsertBulk) ClearMonthlyLimitUsd() *GroupUpsertBulk {
})
}
// SetDefaultValidityDays sets the "default_validity_days" field.
func (u *GroupUpsertBulk) SetDefaultValidityDays(v int) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.SetDefaultValidityDays(v)
})
}
// AddDefaultValidityDays adds v to the "default_validity_days" field.
func (u *GroupUpsertBulk) AddDefaultValidityDays(v int) *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.AddDefaultValidityDays(v)
})
}
// UpdateDefaultValidityDays sets the "default_validity_days" field to the value that was provided on create.
func (u *GroupUpsertBulk) UpdateDefaultValidityDays() *GroupUpsertBulk {
return u.Update(func(s *GroupUpsert) {
s.UpdateDefaultValidityDays()
})
}
// Exec executes the query.
func (u *GroupUpsertBulk) Exec(ctx context.Context) error {
if u.create.err != nil {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment