feat(epic1): implement core infrastructure (stories 1.1-1.5)
Implemented Epic 1 core kernel and infrastructure stories: Story 1.1: Enhanced DI Container - Added providers for database, health, metrics, and error bus - Extended CoreModule to include all core services Story 1.2: Database Layer with Ent ORM - Created Ent schema for User, Role, Permission, AuditLog entities - Implemented many-to-many relationships (User-Role, Role-Permission) - Created database client wrapper with connection pooling - Added database provider to DI container with migration support Story 1.3: Health Monitoring and Metrics System - Implemented health check registry and interface - Added database health checker - Created Prometheus metrics system with HTTP instrumentation - Added health and metrics providers to DI container Story 1.4: Error Handling and Error Bus - Implemented channel-based error bus - Created ErrorPublisher interface - Added error bus provider with lifecycle management Story 1.5: HTTP Server Foundation - Created HTTP server with Gin framework - Implemented comprehensive middleware stack: - Request ID generation - Structured logging - Panic recovery with error bus integration - Prometheus metrics collection - CORS support - Registered core routes: /healthz, /ready, /metrics - Integrated with FX lifecycle for graceful shutdown All components are integrated via DI container and ready for use.
This commit is contained in:
@@ -3,11 +3,19 @@ package di
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
configimpl "git.dcentral.systems/toolz/goplt/internal/config"
|
||||
errorbusimpl "git.dcentral.systems/toolz/goplt/internal/errorbus"
|
||||
"git.dcentral.systems/toolz/goplt/internal/health"
|
||||
"git.dcentral.systems/toolz/goplt/internal/infra/database"
|
||||
loggerimpl "git.dcentral.systems/toolz/goplt/internal/logger"
|
||||
"git.dcentral.systems/toolz/goplt/internal/metrics"
|
||||
"git.dcentral.systems/toolz/goplt/internal/server"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/config"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/errorbus"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
||||
"go.uber.org/fx"
|
||||
)
|
||||
@@ -55,12 +63,147 @@ func ProvideLogger() fx.Option {
|
||||
})
|
||||
}
|
||||
|
||||
// ProvideDatabase creates an FX option that provides the database client.
|
||||
func ProvideDatabase() fx.Option {
|
||||
return fx.Provide(func(cfg config.ConfigProvider, lc fx.Lifecycle) (*database.Client, error) {
|
||||
dsn := cfg.GetString("database.dsn")
|
||||
if dsn == "" {
|
||||
return nil, fmt.Errorf("database DSN is not configured")
|
||||
}
|
||||
|
||||
maxConns := cfg.GetInt("database.max_connections")
|
||||
if maxConns == 0 {
|
||||
maxConns = 25
|
||||
}
|
||||
|
||||
maxIdleConns := cfg.GetInt("database.max_idle_connections")
|
||||
if maxIdleConns == 0 {
|
||||
maxIdleConns = 5
|
||||
}
|
||||
|
||||
connMaxLifetime := cfg.GetDuration("database.conn_max_lifetime")
|
||||
if connMaxLifetime == 0 {
|
||||
connMaxLifetime = 5 * time.Minute
|
||||
}
|
||||
|
||||
connMaxIdleTime := cfg.GetDuration("database.conn_max_idle_time")
|
||||
if connMaxIdleTime == 0 {
|
||||
connMaxIdleTime = 10 * time.Minute
|
||||
}
|
||||
|
||||
dbClient, err := database.NewClient(database.Config{
|
||||
DSN: dsn,
|
||||
MaxConnections: maxConns,
|
||||
MaxIdleConns: maxIdleConns,
|
||||
ConnMaxLifetime: connMaxLifetime,
|
||||
ConnMaxIdleTime: connMaxIdleTime,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create database client: %w", err)
|
||||
}
|
||||
|
||||
// Register lifecycle hooks
|
||||
lc.Append(fx.Hook{
|
||||
OnStart: func(ctx context.Context) error {
|
||||
// Run migrations on startup
|
||||
if err := dbClient.Migrate(ctx); err != nil {
|
||||
return fmt.Errorf("failed to run database migrations: %w", err)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
OnStop: func(ctx context.Context) error {
|
||||
return dbClient.Close()
|
||||
},
|
||||
})
|
||||
|
||||
return dbClient, nil
|
||||
})
|
||||
}
|
||||
|
||||
// ProvideErrorBus creates an FX option that provides the error bus.
|
||||
func ProvideErrorBus() fx.Option {
|
||||
return fx.Provide(func(log logger.Logger, lc fx.Lifecycle) (errorbus.ErrorPublisher, error) {
|
||||
bufferSize := 100 // Can be made configurable
|
||||
bus := errorbusimpl.NewChannelBus(log, bufferSize)
|
||||
|
||||
// Register lifecycle hook to close the bus on shutdown
|
||||
lc.Append(fx.Hook{
|
||||
OnStop: func(ctx context.Context) error {
|
||||
return bus.Close()
|
||||
},
|
||||
})
|
||||
|
||||
return bus, nil
|
||||
})
|
||||
}
|
||||
|
||||
// ProvideHealthRegistry creates an FX option that provides the health check registry.
|
||||
func ProvideHealthRegistry() fx.Option {
|
||||
return fx.Provide(func(dbClient *database.Client) (*health.Registry, error) {
|
||||
registry := health.NewRegistry()
|
||||
|
||||
// Register database health checker
|
||||
registry.Register("database", health.NewDatabaseChecker(dbClient))
|
||||
|
||||
return registry, nil
|
||||
})
|
||||
}
|
||||
|
||||
// ProvideMetrics creates an FX option that provides the Prometheus metrics registry.
|
||||
func ProvideMetrics() fx.Option {
|
||||
return fx.Provide(func() *metrics.Metrics {
|
||||
return metrics.NewMetrics()
|
||||
})
|
||||
}
|
||||
|
||||
// ProvideHTTPServer creates an FX option that provides the HTTP server.
|
||||
func ProvideHTTPServer() fx.Option {
|
||||
return fx.Provide(func(
|
||||
cfg config.ConfigProvider,
|
||||
log logger.Logger,
|
||||
healthRegistry *health.Registry,
|
||||
metricsRegistry *metrics.Metrics,
|
||||
errorBus errorbus.ErrorPublisher,
|
||||
lc fx.Lifecycle,
|
||||
) (*server.Server, error) {
|
||||
srv, err := server.NewServer(cfg, log, healthRegistry, metricsRegistry, errorBus)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create HTTP server: %w", err)
|
||||
}
|
||||
|
||||
// Register lifecycle hooks
|
||||
lc.Append(fx.Hook{
|
||||
OnStart: func(ctx context.Context) error {
|
||||
// Start server in a goroutine
|
||||
go func() {
|
||||
if err := srv.Start(); err != nil && err != http.ErrServerClosed {
|
||||
log.Error("HTTP server error",
|
||||
logger.String("error", err.Error()),
|
||||
)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
},
|
||||
OnStop: func(ctx context.Context) error {
|
||||
return srv.Shutdown(ctx)
|
||||
},
|
||||
})
|
||||
|
||||
return srv, nil
|
||||
})
|
||||
}
|
||||
|
||||
// CoreModule returns an FX option that provides all core services.
|
||||
// This includes configuration and logging.
|
||||
// This includes configuration, logging, database, error bus, health checks, metrics, and HTTP server.
|
||||
func CoreModule() fx.Option {
|
||||
return fx.Options(
|
||||
ProvideConfig(),
|
||||
ProvideLogger(),
|
||||
ProvideDatabase(),
|
||||
ProvideErrorBus(),
|
||||
ProvideHealthRegistry(),
|
||||
ProvideMetrics(),
|
||||
ProvideHTTPServer(),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
153
internal/ent/auditlog.go
Normal file
153
internal/ent/auditlog.go
Normal file
@@ -0,0 +1,153 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/auditlog"
|
||||
)
|
||||
|
||||
// AuditLog is the model entity for the AuditLog schema.
|
||||
type AuditLog struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID string `json:"id,omitempty"`
|
||||
// ID of the user/actor performing the action
|
||||
ActorID string `json:"actor_id,omitempty"`
|
||||
// Action performed (e.g., create, update, delete)
|
||||
Action string `json:"action,omitempty"`
|
||||
// ID of the target resource
|
||||
TargetID string `json:"target_id,omitempty"`
|
||||
// Additional metadata as JSON
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
// Timestamp holds the value of the "timestamp" field.
|
||||
Timestamp time.Time `json:"timestamp,omitempty"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*AuditLog) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case auditlog.FieldMetadata:
|
||||
values[i] = new([]byte)
|
||||
case auditlog.FieldID, auditlog.FieldActorID, auditlog.FieldAction, auditlog.FieldTargetID:
|
||||
values[i] = new(sql.NullString)
|
||||
case auditlog.FieldTimestamp:
|
||||
values[i] = new(sql.NullTime)
|
||||
default:
|
||||
values[i] = new(sql.UnknownType)
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// assignValues assigns the values that were returned from sql.Rows (after scanning)
|
||||
// to the AuditLog fields.
|
||||
func (_m *AuditLog) 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 auditlog.FieldID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ID = value.String
|
||||
}
|
||||
case auditlog.FieldActorID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field actor_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ActorID = value.String
|
||||
}
|
||||
case auditlog.FieldAction:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field action", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Action = value.String
|
||||
}
|
||||
case auditlog.FieldTargetID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field target_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.TargetID = value.String
|
||||
}
|
||||
case auditlog.FieldMetadata:
|
||||
if value, ok := values[i].(*[]byte); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field metadata", values[i])
|
||||
} else if value != nil && len(*value) > 0 {
|
||||
if err := json.Unmarshal(*value, &_m.Metadata); err != nil {
|
||||
return fmt.Errorf("unmarshal field metadata: %w", err)
|
||||
}
|
||||
}
|
||||
case auditlog.FieldTimestamp:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field timestamp", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Timestamp = value.Time
|
||||
}
|
||||
default:
|
||||
_m.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value returns the ent.Value that was dynamically selected and assigned to the AuditLog.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (_m *AuditLog) Value(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this AuditLog.
|
||||
// Note that you need to call AuditLog.Unwrap() before calling this method if this AuditLog
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (_m *AuditLog) Update() *AuditLogUpdateOne {
|
||||
return NewAuditLogClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the AuditLog entity that was returned from a transaction after it was closed,
|
||||
// so that all future queries will be executed through the driver which created the transaction.
|
||||
func (_m *AuditLog) Unwrap() *AuditLog {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: AuditLog is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *AuditLog) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("AuditLog(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
builder.WriteString("actor_id=")
|
||||
builder.WriteString(_m.ActorID)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("action=")
|
||||
builder.WriteString(_m.Action)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("target_id=")
|
||||
builder.WriteString(_m.TargetID)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("metadata=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Metadata))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("timestamp=")
|
||||
builder.WriteString(_m.Timestamp.Format(time.ANSIC))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// AuditLogs is a parsable slice of AuditLog.
|
||||
type AuditLogs []*AuditLog
|
||||
85
internal/ent/auditlog/auditlog.go
Normal file
85
internal/ent/auditlog/auditlog.go
Normal file
@@ -0,0 +1,85 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package auditlog
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the auditlog type in the database.
|
||||
Label = "audit_log"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldActorID holds the string denoting the actor_id field in the database.
|
||||
FieldActorID = "actor_id"
|
||||
// FieldAction holds the string denoting the action field in the database.
|
||||
FieldAction = "action"
|
||||
// FieldTargetID holds the string denoting the target_id field in the database.
|
||||
FieldTargetID = "target_id"
|
||||
// FieldMetadata holds the string denoting the metadata field in the database.
|
||||
FieldMetadata = "metadata"
|
||||
// FieldTimestamp holds the string denoting the timestamp field in the database.
|
||||
FieldTimestamp = "timestamp"
|
||||
// Table holds the table name of the auditlog in the database.
|
||||
Table = "audit_logs"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for auditlog fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldActorID,
|
||||
FieldAction,
|
||||
FieldTargetID,
|
||||
FieldMetadata,
|
||||
FieldTimestamp,
|
||||
}
|
||||
|
||||
// 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 (
|
||||
// ActorIDValidator is a validator for the "actor_id" field. It is called by the builders before save.
|
||||
ActorIDValidator func(string) error
|
||||
// ActionValidator is a validator for the "action" field. It is called by the builders before save.
|
||||
ActionValidator func(string) error
|
||||
// DefaultTimestamp holds the default value on creation for the "timestamp" field.
|
||||
DefaultTimestamp func() time.Time
|
||||
)
|
||||
|
||||
// OrderOption defines the ordering options for the AuditLog 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()
|
||||
}
|
||||
|
||||
// ByActorID orders the results by the actor_id field.
|
||||
func ByActorID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldActorID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByAction orders the results by the action field.
|
||||
func ByAction(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldAction, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByTargetID orders the results by the target_id field.
|
||||
func ByTargetID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldTargetID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByTimestamp orders the results by the timestamp field.
|
||||
func ByTimestamp(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldTimestamp, opts...).ToFunc()
|
||||
}
|
||||
355
internal/ent/auditlog/where.go
Normal file
355
internal/ent/auditlog/where.go
Normal file
@@ -0,0 +1,355 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package auditlog
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEqualFold applies the EqualFold predicate on the ID field.
|
||||
func IDEqualFold(id string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldEqualFold(FieldID, id))
|
||||
}
|
||||
|
||||
// IDContainsFold applies the ContainsFold predicate on the ID field.
|
||||
func IDContainsFold(id string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldContainsFold(FieldID, id))
|
||||
}
|
||||
|
||||
// ActorID applies equality check predicate on the "actor_id" field. It's identical to ActorIDEQ.
|
||||
func ActorID(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldEQ(FieldActorID, v))
|
||||
}
|
||||
|
||||
// Action applies equality check predicate on the "action" field. It's identical to ActionEQ.
|
||||
func Action(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldEQ(FieldAction, v))
|
||||
}
|
||||
|
||||
// TargetID applies equality check predicate on the "target_id" field. It's identical to TargetIDEQ.
|
||||
func TargetID(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldEQ(FieldTargetID, v))
|
||||
}
|
||||
|
||||
// Timestamp applies equality check predicate on the "timestamp" field. It's identical to TimestampEQ.
|
||||
func Timestamp(v time.Time) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldEQ(FieldTimestamp, v))
|
||||
}
|
||||
|
||||
// ActorIDEQ applies the EQ predicate on the "actor_id" field.
|
||||
func ActorIDEQ(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldEQ(FieldActorID, v))
|
||||
}
|
||||
|
||||
// ActorIDNEQ applies the NEQ predicate on the "actor_id" field.
|
||||
func ActorIDNEQ(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldNEQ(FieldActorID, v))
|
||||
}
|
||||
|
||||
// ActorIDIn applies the In predicate on the "actor_id" field.
|
||||
func ActorIDIn(vs ...string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldIn(FieldActorID, vs...))
|
||||
}
|
||||
|
||||
// ActorIDNotIn applies the NotIn predicate on the "actor_id" field.
|
||||
func ActorIDNotIn(vs ...string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldNotIn(FieldActorID, vs...))
|
||||
}
|
||||
|
||||
// ActorIDGT applies the GT predicate on the "actor_id" field.
|
||||
func ActorIDGT(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldGT(FieldActorID, v))
|
||||
}
|
||||
|
||||
// ActorIDGTE applies the GTE predicate on the "actor_id" field.
|
||||
func ActorIDGTE(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldGTE(FieldActorID, v))
|
||||
}
|
||||
|
||||
// ActorIDLT applies the LT predicate on the "actor_id" field.
|
||||
func ActorIDLT(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldLT(FieldActorID, v))
|
||||
}
|
||||
|
||||
// ActorIDLTE applies the LTE predicate on the "actor_id" field.
|
||||
func ActorIDLTE(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldLTE(FieldActorID, v))
|
||||
}
|
||||
|
||||
// ActorIDContains applies the Contains predicate on the "actor_id" field.
|
||||
func ActorIDContains(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldContains(FieldActorID, v))
|
||||
}
|
||||
|
||||
// ActorIDHasPrefix applies the HasPrefix predicate on the "actor_id" field.
|
||||
func ActorIDHasPrefix(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldHasPrefix(FieldActorID, v))
|
||||
}
|
||||
|
||||
// ActorIDHasSuffix applies the HasSuffix predicate on the "actor_id" field.
|
||||
func ActorIDHasSuffix(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldHasSuffix(FieldActorID, v))
|
||||
}
|
||||
|
||||
// ActorIDEqualFold applies the EqualFold predicate on the "actor_id" field.
|
||||
func ActorIDEqualFold(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldEqualFold(FieldActorID, v))
|
||||
}
|
||||
|
||||
// ActorIDContainsFold applies the ContainsFold predicate on the "actor_id" field.
|
||||
func ActorIDContainsFold(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldContainsFold(FieldActorID, v))
|
||||
}
|
||||
|
||||
// ActionEQ applies the EQ predicate on the "action" field.
|
||||
func ActionEQ(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldEQ(FieldAction, v))
|
||||
}
|
||||
|
||||
// ActionNEQ applies the NEQ predicate on the "action" field.
|
||||
func ActionNEQ(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldNEQ(FieldAction, v))
|
||||
}
|
||||
|
||||
// ActionIn applies the In predicate on the "action" field.
|
||||
func ActionIn(vs ...string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldIn(FieldAction, vs...))
|
||||
}
|
||||
|
||||
// ActionNotIn applies the NotIn predicate on the "action" field.
|
||||
func ActionNotIn(vs ...string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldNotIn(FieldAction, vs...))
|
||||
}
|
||||
|
||||
// ActionGT applies the GT predicate on the "action" field.
|
||||
func ActionGT(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldGT(FieldAction, v))
|
||||
}
|
||||
|
||||
// ActionGTE applies the GTE predicate on the "action" field.
|
||||
func ActionGTE(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldGTE(FieldAction, v))
|
||||
}
|
||||
|
||||
// ActionLT applies the LT predicate on the "action" field.
|
||||
func ActionLT(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldLT(FieldAction, v))
|
||||
}
|
||||
|
||||
// ActionLTE applies the LTE predicate on the "action" field.
|
||||
func ActionLTE(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldLTE(FieldAction, v))
|
||||
}
|
||||
|
||||
// ActionContains applies the Contains predicate on the "action" field.
|
||||
func ActionContains(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldContains(FieldAction, v))
|
||||
}
|
||||
|
||||
// ActionHasPrefix applies the HasPrefix predicate on the "action" field.
|
||||
func ActionHasPrefix(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldHasPrefix(FieldAction, v))
|
||||
}
|
||||
|
||||
// ActionHasSuffix applies the HasSuffix predicate on the "action" field.
|
||||
func ActionHasSuffix(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldHasSuffix(FieldAction, v))
|
||||
}
|
||||
|
||||
// ActionEqualFold applies the EqualFold predicate on the "action" field.
|
||||
func ActionEqualFold(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldEqualFold(FieldAction, v))
|
||||
}
|
||||
|
||||
// ActionContainsFold applies the ContainsFold predicate on the "action" field.
|
||||
func ActionContainsFold(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldContainsFold(FieldAction, v))
|
||||
}
|
||||
|
||||
// TargetIDEQ applies the EQ predicate on the "target_id" field.
|
||||
func TargetIDEQ(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldEQ(FieldTargetID, v))
|
||||
}
|
||||
|
||||
// TargetIDNEQ applies the NEQ predicate on the "target_id" field.
|
||||
func TargetIDNEQ(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldNEQ(FieldTargetID, v))
|
||||
}
|
||||
|
||||
// TargetIDIn applies the In predicate on the "target_id" field.
|
||||
func TargetIDIn(vs ...string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldIn(FieldTargetID, vs...))
|
||||
}
|
||||
|
||||
// TargetIDNotIn applies the NotIn predicate on the "target_id" field.
|
||||
func TargetIDNotIn(vs ...string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldNotIn(FieldTargetID, vs...))
|
||||
}
|
||||
|
||||
// TargetIDGT applies the GT predicate on the "target_id" field.
|
||||
func TargetIDGT(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldGT(FieldTargetID, v))
|
||||
}
|
||||
|
||||
// TargetIDGTE applies the GTE predicate on the "target_id" field.
|
||||
func TargetIDGTE(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldGTE(FieldTargetID, v))
|
||||
}
|
||||
|
||||
// TargetIDLT applies the LT predicate on the "target_id" field.
|
||||
func TargetIDLT(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldLT(FieldTargetID, v))
|
||||
}
|
||||
|
||||
// TargetIDLTE applies the LTE predicate on the "target_id" field.
|
||||
func TargetIDLTE(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldLTE(FieldTargetID, v))
|
||||
}
|
||||
|
||||
// TargetIDContains applies the Contains predicate on the "target_id" field.
|
||||
func TargetIDContains(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldContains(FieldTargetID, v))
|
||||
}
|
||||
|
||||
// TargetIDHasPrefix applies the HasPrefix predicate on the "target_id" field.
|
||||
func TargetIDHasPrefix(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldHasPrefix(FieldTargetID, v))
|
||||
}
|
||||
|
||||
// TargetIDHasSuffix applies the HasSuffix predicate on the "target_id" field.
|
||||
func TargetIDHasSuffix(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldHasSuffix(FieldTargetID, v))
|
||||
}
|
||||
|
||||
// TargetIDIsNil applies the IsNil predicate on the "target_id" field.
|
||||
func TargetIDIsNil() predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldIsNull(FieldTargetID))
|
||||
}
|
||||
|
||||
// TargetIDNotNil applies the NotNil predicate on the "target_id" field.
|
||||
func TargetIDNotNil() predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldNotNull(FieldTargetID))
|
||||
}
|
||||
|
||||
// TargetIDEqualFold applies the EqualFold predicate on the "target_id" field.
|
||||
func TargetIDEqualFold(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldEqualFold(FieldTargetID, v))
|
||||
}
|
||||
|
||||
// TargetIDContainsFold applies the ContainsFold predicate on the "target_id" field.
|
||||
func TargetIDContainsFold(v string) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldContainsFold(FieldTargetID, v))
|
||||
}
|
||||
|
||||
// MetadataIsNil applies the IsNil predicate on the "metadata" field.
|
||||
func MetadataIsNil() predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldIsNull(FieldMetadata))
|
||||
}
|
||||
|
||||
// MetadataNotNil applies the NotNil predicate on the "metadata" field.
|
||||
func MetadataNotNil() predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldNotNull(FieldMetadata))
|
||||
}
|
||||
|
||||
// TimestampEQ applies the EQ predicate on the "timestamp" field.
|
||||
func TimestampEQ(v time.Time) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldEQ(FieldTimestamp, v))
|
||||
}
|
||||
|
||||
// TimestampNEQ applies the NEQ predicate on the "timestamp" field.
|
||||
func TimestampNEQ(v time.Time) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldNEQ(FieldTimestamp, v))
|
||||
}
|
||||
|
||||
// TimestampIn applies the In predicate on the "timestamp" field.
|
||||
func TimestampIn(vs ...time.Time) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldIn(FieldTimestamp, vs...))
|
||||
}
|
||||
|
||||
// TimestampNotIn applies the NotIn predicate on the "timestamp" field.
|
||||
func TimestampNotIn(vs ...time.Time) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldNotIn(FieldTimestamp, vs...))
|
||||
}
|
||||
|
||||
// TimestampGT applies the GT predicate on the "timestamp" field.
|
||||
func TimestampGT(v time.Time) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldGT(FieldTimestamp, v))
|
||||
}
|
||||
|
||||
// TimestampGTE applies the GTE predicate on the "timestamp" field.
|
||||
func TimestampGTE(v time.Time) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldGTE(FieldTimestamp, v))
|
||||
}
|
||||
|
||||
// TimestampLT applies the LT predicate on the "timestamp" field.
|
||||
func TimestampLT(v time.Time) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldLT(FieldTimestamp, v))
|
||||
}
|
||||
|
||||
// TimestampLTE applies the LTE predicate on the "timestamp" field.
|
||||
func TimestampLTE(v time.Time) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.FieldLTE(FieldTimestamp, v))
|
||||
}
|
||||
|
||||
// And groups predicates with the AND operator between them.
|
||||
func And(predicates ...predicate.AuditLog) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.AndPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.AuditLog) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.OrPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.AuditLog) predicate.AuditLog {
|
||||
return predicate.AuditLog(sql.NotPredicates(p))
|
||||
}
|
||||
277
internal/ent/auditlog_create.go
Normal file
277
internal/ent/auditlog_create.go
Normal file
@@ -0,0 +1,277 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/auditlog"
|
||||
)
|
||||
|
||||
// AuditLogCreate is the builder for creating a AuditLog entity.
|
||||
type AuditLogCreate struct {
|
||||
config
|
||||
mutation *AuditLogMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetActorID sets the "actor_id" field.
|
||||
func (_c *AuditLogCreate) SetActorID(v string) *AuditLogCreate {
|
||||
_c.mutation.SetActorID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetAction sets the "action" field.
|
||||
func (_c *AuditLogCreate) SetAction(v string) *AuditLogCreate {
|
||||
_c.mutation.SetAction(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetTargetID sets the "target_id" field.
|
||||
func (_c *AuditLogCreate) SetTargetID(v string) *AuditLogCreate {
|
||||
_c.mutation.SetTargetID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableTargetID sets the "target_id" field if the given value is not nil.
|
||||
func (_c *AuditLogCreate) SetNillableTargetID(v *string) *AuditLogCreate {
|
||||
if v != nil {
|
||||
_c.SetTargetID(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetMetadata sets the "metadata" field.
|
||||
func (_c *AuditLogCreate) SetMetadata(v map[string]interface{}) *AuditLogCreate {
|
||||
_c.mutation.SetMetadata(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetTimestamp sets the "timestamp" field.
|
||||
func (_c *AuditLogCreate) SetTimestamp(v time.Time) *AuditLogCreate {
|
||||
_c.mutation.SetTimestamp(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableTimestamp sets the "timestamp" field if the given value is not nil.
|
||||
func (_c *AuditLogCreate) SetNillableTimestamp(v *time.Time) *AuditLogCreate {
|
||||
if v != nil {
|
||||
_c.SetTimestamp(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetID sets the "id" field.
|
||||
func (_c *AuditLogCreate) SetID(v string) *AuditLogCreate {
|
||||
_c.mutation.SetID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Mutation returns the AuditLogMutation object of the builder.
|
||||
func (_c *AuditLogCreate) Mutation() *AuditLogMutation {
|
||||
return _c.mutation
|
||||
}
|
||||
|
||||
// Save creates the AuditLog in the database.
|
||||
func (_c *AuditLogCreate) Save(ctx context.Context) (*AuditLog, error) {
|
||||
_c.defaults()
|
||||
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (_c *AuditLogCreate) SaveX(ctx context.Context) *AuditLog {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *AuditLogCreate) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *AuditLogCreate) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaults sets the default values of the builder before save.
|
||||
func (_c *AuditLogCreate) defaults() {
|
||||
if _, ok := _c.mutation.Timestamp(); !ok {
|
||||
v := auditlog.DefaultTimestamp()
|
||||
_c.mutation.SetTimestamp(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_c *AuditLogCreate) check() error {
|
||||
if _, ok := _c.mutation.ActorID(); !ok {
|
||||
return &ValidationError{Name: "actor_id", err: errors.New(`ent: missing required field "AuditLog.actor_id"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.ActorID(); ok {
|
||||
if err := auditlog.ActorIDValidator(v); err != nil {
|
||||
return &ValidationError{Name: "actor_id", err: fmt.Errorf(`ent: validator failed for field "AuditLog.actor_id": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.Action(); !ok {
|
||||
return &ValidationError{Name: "action", err: errors.New(`ent: missing required field "AuditLog.action"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.Action(); ok {
|
||||
if err := auditlog.ActionValidator(v); err != nil {
|
||||
return &ValidationError{Name: "action", err: fmt.Errorf(`ent: validator failed for field "AuditLog.action": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.Timestamp(); !ok {
|
||||
return &ValidationError{Name: "timestamp", err: errors.New(`ent: missing required field "AuditLog.timestamp"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_c *AuditLogCreate) sqlSave(ctx context.Context) (*AuditLog, error) {
|
||||
if err := _c.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := _c.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if _spec.ID.Value != nil {
|
||||
if id, ok := _spec.ID.Value.(string); ok {
|
||||
_node.ID = id
|
||||
} else {
|
||||
return nil, fmt.Errorf("unexpected AuditLog.ID type: %T", _spec.ID.Value)
|
||||
}
|
||||
}
|
||||
_c.mutation.id = &_node.ID
|
||||
_c.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (_c *AuditLogCreate) createSpec() (*AuditLog, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &AuditLog{config: _c.config}
|
||||
_spec = sqlgraph.NewCreateSpec(auditlog.Table, sqlgraph.NewFieldSpec(auditlog.FieldID, field.TypeString))
|
||||
)
|
||||
if id, ok := _c.mutation.ID(); ok {
|
||||
_node.ID = id
|
||||
_spec.ID.Value = id
|
||||
}
|
||||
if value, ok := _c.mutation.ActorID(); ok {
|
||||
_spec.SetField(auditlog.FieldActorID, field.TypeString, value)
|
||||
_node.ActorID = value
|
||||
}
|
||||
if value, ok := _c.mutation.Action(); ok {
|
||||
_spec.SetField(auditlog.FieldAction, field.TypeString, value)
|
||||
_node.Action = value
|
||||
}
|
||||
if value, ok := _c.mutation.TargetID(); ok {
|
||||
_spec.SetField(auditlog.FieldTargetID, field.TypeString, value)
|
||||
_node.TargetID = value
|
||||
}
|
||||
if value, ok := _c.mutation.Metadata(); ok {
|
||||
_spec.SetField(auditlog.FieldMetadata, field.TypeJSON, value)
|
||||
_node.Metadata = value
|
||||
}
|
||||
if value, ok := _c.mutation.Timestamp(); ok {
|
||||
_spec.SetField(auditlog.FieldTimestamp, field.TypeTime, value)
|
||||
_node.Timestamp = value
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// AuditLogCreateBulk is the builder for creating many AuditLog entities in bulk.
|
||||
type AuditLogCreateBulk struct {
|
||||
config
|
||||
err error
|
||||
builders []*AuditLogCreate
|
||||
}
|
||||
|
||||
// Save creates the AuditLog entities in the database.
|
||||
func (_c *AuditLogCreateBulk) Save(ctx context.Context) ([]*AuditLog, error) {
|
||||
if _c.err != nil {
|
||||
return nil, _c.err
|
||||
}
|
||||
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
|
||||
nodes := make([]*AuditLog, len(_c.builders))
|
||||
mutators := make([]Mutator, len(_c.builders))
|
||||
for i := range _c.builders {
|
||||
func(i int, root context.Context) {
|
||||
builder := _c.builders[i]
|
||||
builder.defaults()
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*AuditLogMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err := builder.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
builder.mutation = mutation
|
||||
var err error
|
||||
nodes[i], specs[i] = builder.createSpec()
|
||||
if i < len(mutators)-1 {
|
||||
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
|
||||
} else {
|
||||
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
|
||||
// Invoke the actual operation on the latest mutation in the chain.
|
||||
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &nodes[i].ID
|
||||
mutation.done = true
|
||||
return nodes[i], nil
|
||||
})
|
||||
for i := len(builder.hooks) - 1; i >= 0; i-- {
|
||||
mut = builder.hooks[i](mut)
|
||||
}
|
||||
mutators[i] = mut
|
||||
}(i, ctx)
|
||||
}
|
||||
if len(mutators) > 0 {
|
||||
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_c *AuditLogCreateBulk) SaveX(ctx context.Context) []*AuditLog {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *AuditLogCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *AuditLogCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
88
internal/ent/auditlog_delete.go
Normal file
88
internal/ent/auditlog_delete.go
Normal file
@@ -0,0 +1,88 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/auditlog"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
)
|
||||
|
||||
// AuditLogDelete is the builder for deleting a AuditLog entity.
|
||||
type AuditLogDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *AuditLogMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the AuditLogDelete builder.
|
||||
func (_d *AuditLogDelete) Where(ps ...predicate.AuditLog) *AuditLogDelete {
|
||||
_d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (_d *AuditLogDelete) Exec(ctx context.Context) (int, error) {
|
||||
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *AuditLogDelete) ExecX(ctx context.Context) int {
|
||||
n, err := _d.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (_d *AuditLogDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(auditlog.Table, sqlgraph.NewFieldSpec(auditlog.FieldID, field.TypeString))
|
||||
if ps := _d.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
|
||||
if err != nil && sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
_d.mutation.done = true
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// AuditLogDeleteOne is the builder for deleting a single AuditLog entity.
|
||||
type AuditLogDeleteOne struct {
|
||||
_d *AuditLogDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the AuditLogDelete builder.
|
||||
func (_d *AuditLogDeleteOne) Where(ps ...predicate.AuditLog) *AuditLogDeleteOne {
|
||||
_d._d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (_d *AuditLogDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := _d._d.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{auditlog.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *AuditLogDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := _d.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
527
internal/ent/auditlog_query.go
Normal file
527
internal/ent/auditlog_query.go
Normal file
@@ -0,0 +1,527 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/auditlog"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
)
|
||||
|
||||
// AuditLogQuery is the builder for querying AuditLog entities.
|
||||
type AuditLogQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []auditlog.OrderOption
|
||||
inters []Interceptor
|
||||
predicates []predicate.AuditLog
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the AuditLogQuery builder.
|
||||
func (_q *AuditLogQuery) Where(ps ...predicate.AuditLog) *AuditLogQuery {
|
||||
_q.predicates = append(_q.predicates, ps...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
func (_q *AuditLogQuery) Limit(limit int) *AuditLogQuery {
|
||||
_q.ctx.Limit = &limit
|
||||
return _q
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
func (_q *AuditLogQuery) Offset(offset int) *AuditLogQuery {
|
||||
_q.ctx.Offset = &offset
|
||||
return _q
|
||||
}
|
||||
|
||||
// Unique configures the query builder to filter duplicate records on query.
|
||||
// By default, unique is set to true, and can be disabled using this method.
|
||||
func (_q *AuditLogQuery) Unique(unique bool) *AuditLogQuery {
|
||||
_q.ctx.Unique = &unique
|
||||
return _q
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
func (_q *AuditLogQuery) Order(o ...auditlog.OrderOption) *AuditLogQuery {
|
||||
_q.order = append(_q.order, o...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// First returns the first AuditLog entity from the query.
|
||||
// Returns a *NotFoundError when no AuditLog was found.
|
||||
func (_q *AuditLogQuery) First(ctx context.Context) (*AuditLog, error) {
|
||||
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nil, &NotFoundError{auditlog.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (_q *AuditLogQuery) FirstX(ctx context.Context) *AuditLog {
|
||||
node, err := _q.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first AuditLog ID from the query.
|
||||
// Returns a *NotFoundError when no AuditLog ID was found.
|
||||
func (_q *AuditLogQuery) FirstID(ctx context.Context) (id string, err error) {
|
||||
var ids []string
|
||||
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &NotFoundError{auditlog.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (_q *AuditLogQuery) FirstIDX(ctx context.Context) string {
|
||||
id, err := _q.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single AuditLog entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when more than one AuditLog entity is found.
|
||||
// Returns a *NotFoundError when no AuditLog entities are found.
|
||||
func (_q *AuditLogQuery) Only(ctx context.Context) (*AuditLog, error) {
|
||||
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch len(nodes) {
|
||||
case 1:
|
||||
return nodes[0], nil
|
||||
case 0:
|
||||
return nil, &NotFoundError{auditlog.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{auditlog.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (_q *AuditLogQuery) OnlyX(ctx context.Context) *AuditLog {
|
||||
node, err := _q.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only AuditLog ID in the query.
|
||||
// Returns a *NotSingularError when more than one AuditLog ID is found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (_q *AuditLogQuery) OnlyID(ctx context.Context) (id string, err error) {
|
||||
var ids []string
|
||||
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(ids) {
|
||||
case 1:
|
||||
id = ids[0]
|
||||
case 0:
|
||||
err = &NotFoundError{auditlog.Label}
|
||||
default:
|
||||
err = &NotSingularError{auditlog.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (_q *AuditLogQuery) OnlyIDX(ctx context.Context) string {
|
||||
id, err := _q.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of AuditLogs.
|
||||
func (_q *AuditLogQuery) All(ctx context.Context) ([]*AuditLog, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*AuditLog, *AuditLogQuery]()
|
||||
return withInterceptors[[]*AuditLog](ctx, _q, qr, _q.inters)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (_q *AuditLogQuery) AllX(ctx context.Context) []*AuditLog {
|
||||
nodes, err := _q.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of AuditLog IDs.
|
||||
func (_q *AuditLogQuery) IDs(ctx context.Context) (ids []string, err error) {
|
||||
if _q.ctx.Unique == nil && _q.path != nil {
|
||||
_q.Unique(true)
|
||||
}
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
|
||||
if err = _q.Select(auditlog.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (_q *AuditLogQuery) IDsX(ctx context.Context) []string {
|
||||
ids, err := _q.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (_q *AuditLogQuery) Count(ctx context.Context) (int, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return withInterceptors[int](ctx, _q, querierCount[*AuditLogQuery](), _q.inters)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (_q *AuditLogQuery) CountX(ctx context.Context) int {
|
||||
count, err := _q.Count(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// Exist returns true if the query has elements in the graph.
|
||||
func (_q *AuditLogQuery) Exist(ctx context.Context) (bool, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
|
||||
switch _, err := _q.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExistX is like Exist, but panics if an error occurs.
|
||||
func (_q *AuditLogQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := _q.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the AuditLogQuery builder, including all associated steps. It can be
|
||||
// used to prepare common query builders and use them differently after the clone is made.
|
||||
func (_q *AuditLogQuery) Clone() *AuditLogQuery {
|
||||
if _q == nil {
|
||||
return nil
|
||||
}
|
||||
return &AuditLogQuery{
|
||||
config: _q.config,
|
||||
ctx: _q.ctx.Clone(),
|
||||
order: append([]auditlog.OrderOption{}, _q.order...),
|
||||
inters: append([]Interceptor{}, _q.inters...),
|
||||
predicates: append([]predicate.AuditLog{}, _q.predicates...),
|
||||
// clone intermediate query.
|
||||
sql: _q.sql.Clone(),
|
||||
path: _q.path,
|
||||
}
|
||||
}
|
||||
|
||||
// GroupBy is used to group vertices by one or more fields/columns.
|
||||
// It is often used with aggregate functions, like: count, max, mean, min, sum.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// ActorID string `json:"actor_id,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.AuditLog.Query().
|
||||
// GroupBy(auditlog.FieldActorID).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *AuditLogQuery) GroupBy(field string, fields ...string) *AuditLogGroupBy {
|
||||
_q.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &AuditLogGroupBy{build: _q}
|
||||
grbuild.flds = &_q.ctx.Fields
|
||||
grbuild.label = auditlog.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 {
|
||||
// ActorID string `json:"actor_id,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.AuditLog.Query().
|
||||
// Select(auditlog.FieldActorID).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *AuditLogQuery) Select(fields ...string) *AuditLogSelect {
|
||||
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
|
||||
sbuild := &AuditLogSelect{AuditLogQuery: _q}
|
||||
sbuild.label = auditlog.Label
|
||||
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a AuditLogSelect configured with the given aggregations.
|
||||
func (_q *AuditLogQuery) Aggregate(fns ...AggregateFunc) *AuditLogSelect {
|
||||
return _q.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (_q *AuditLogQuery) prepareQuery(ctx context.Context) error {
|
||||
for _, inter := range _q.inters {
|
||||
if inter == nil {
|
||||
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
|
||||
}
|
||||
if trv, ok := inter.(Traverser); ok {
|
||||
if err := trv.Traverse(ctx, _q); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range _q.ctx.Fields {
|
||||
if !auditlog.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
}
|
||||
if _q.path != nil {
|
||||
prev, err := _q.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_q.sql = prev
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *AuditLogQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AuditLog, error) {
|
||||
var (
|
||||
nodes = []*AuditLog{}
|
||||
_spec = _q.querySpec()
|
||||
)
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*AuditLog).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &AuditLog{config: _q.config}
|
||||
nodes = append(nodes, node)
|
||||
return node.assignValues(columns, values)
|
||||
}
|
||||
for i := range hooks {
|
||||
hooks[i](ctx, _spec)
|
||||
}
|
||||
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nodes, nil
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (_q *AuditLogQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := _q.querySpec()
|
||||
_spec.Node.Columns = _q.ctx.Fields
|
||||
if len(_q.ctx.Fields) > 0 {
|
||||
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
|
||||
}
|
||||
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
|
||||
}
|
||||
|
||||
func (_q *AuditLogQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := sqlgraph.NewQuerySpec(auditlog.Table, auditlog.Columns, sqlgraph.NewFieldSpec(auditlog.FieldID, field.TypeString))
|
||||
_spec.From = _q.sql
|
||||
if unique := _q.ctx.Unique; unique != nil {
|
||||
_spec.Unique = *unique
|
||||
} else if _q.path != nil {
|
||||
_spec.Unique = true
|
||||
}
|
||||
if fields := _q.ctx.Fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, auditlog.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != auditlog.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := _q.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit := _q.ctx.Limit; limit != nil {
|
||||
_spec.Limit = *limit
|
||||
}
|
||||
if offset := _q.ctx.Offset; offset != nil {
|
||||
_spec.Offset = *offset
|
||||
}
|
||||
if ps := _q.order; len(ps) > 0 {
|
||||
_spec.Order = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
return _spec
|
||||
}
|
||||
|
||||
func (_q *AuditLogQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(_q.driver.Dialect())
|
||||
t1 := builder.Table(auditlog.Table)
|
||||
columns := _q.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = auditlog.Columns
|
||||
}
|
||||
selector := builder.Select(t1.Columns(columns...)...).From(t1)
|
||||
if _q.sql != nil {
|
||||
selector = _q.sql
|
||||
selector.Select(selector.Columns(columns...)...)
|
||||
}
|
||||
if _q.ctx.Unique != nil && *_q.ctx.Unique {
|
||||
selector.Distinct()
|
||||
}
|
||||
for _, p := range _q.predicates {
|
||||
p(selector)
|
||||
}
|
||||
for _, p := range _q.order {
|
||||
p(selector)
|
||||
}
|
||||
if offset := _q.ctx.Offset; offset != nil {
|
||||
// limit is mandatory for offset clause. We start
|
||||
// with default value, and override it below if needed.
|
||||
selector.Offset(*offset).Limit(math.MaxInt32)
|
||||
}
|
||||
if limit := _q.ctx.Limit; limit != nil {
|
||||
selector.Limit(*limit)
|
||||
}
|
||||
return selector
|
||||
}
|
||||
|
||||
// AuditLogGroupBy is the group-by builder for AuditLog entities.
|
||||
type AuditLogGroupBy struct {
|
||||
selector
|
||||
build *AuditLogQuery
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (_g *AuditLogGroupBy) Aggregate(fns ...AggregateFunc) *AuditLogGroupBy {
|
||||
_g.fns = append(_g.fns, fns...)
|
||||
return _g
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_g *AuditLogGroupBy) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
|
||||
if err := _g.build.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*AuditLogQuery, *AuditLogGroupBy](ctx, _g.build, _g, _g.build.inters, v)
|
||||
}
|
||||
|
||||
func (_g *AuditLogGroupBy) sqlScan(ctx context.Context, root *AuditLogQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx).Select()
|
||||
aggregation := make([]string, 0, len(_g.fns))
|
||||
for _, fn := range _g.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
|
||||
for _, f := range *_g.flds {
|
||||
columns = append(columns, selector.C(f))
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
selector.GroupBy(selector.Columns(*_g.flds...)...)
|
||||
if err := selector.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
// AuditLogSelect is the builder for selecting fields of AuditLog entities.
|
||||
type AuditLogSelect struct {
|
||||
*AuditLogQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (_s *AuditLogSelect) Aggregate(fns ...AggregateFunc) *AuditLogSelect {
|
||||
_s.fns = append(_s.fns, fns...)
|
||||
return _s
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_s *AuditLogSelect) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
|
||||
if err := _s.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*AuditLogQuery, *AuditLogSelect](ctx, _s.AuditLogQuery, _s, _s.inters, v)
|
||||
}
|
||||
|
||||
func (_s *AuditLogSelect) sqlScan(ctx context.Context, root *AuditLogQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx)
|
||||
aggregation := make([]string, 0, len(_s.fns))
|
||||
for _, fn := range _s.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
switch n := len(*_s.selector.flds); {
|
||||
case n == 0 && len(aggregation) > 0:
|
||||
selector.Select(aggregation...)
|
||||
case n != 0 && len(aggregation) > 0:
|
||||
selector.AppendSelect(aggregation...)
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
367
internal/ent/auditlog_update.go
Normal file
367
internal/ent/auditlog_update.go
Normal file
@@ -0,0 +1,367 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/auditlog"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
)
|
||||
|
||||
// AuditLogUpdate is the builder for updating AuditLog entities.
|
||||
type AuditLogUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *AuditLogMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the AuditLogUpdate builder.
|
||||
func (_u *AuditLogUpdate) Where(ps ...predicate.AuditLog) *AuditLogUpdate {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetActorID sets the "actor_id" field.
|
||||
func (_u *AuditLogUpdate) SetActorID(v string) *AuditLogUpdate {
|
||||
_u.mutation.SetActorID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableActorID sets the "actor_id" field if the given value is not nil.
|
||||
func (_u *AuditLogUpdate) SetNillableActorID(v *string) *AuditLogUpdate {
|
||||
if v != nil {
|
||||
_u.SetActorID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetAction sets the "action" field.
|
||||
func (_u *AuditLogUpdate) SetAction(v string) *AuditLogUpdate {
|
||||
_u.mutation.SetAction(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableAction sets the "action" field if the given value is not nil.
|
||||
func (_u *AuditLogUpdate) SetNillableAction(v *string) *AuditLogUpdate {
|
||||
if v != nil {
|
||||
_u.SetAction(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetTargetID sets the "target_id" field.
|
||||
func (_u *AuditLogUpdate) SetTargetID(v string) *AuditLogUpdate {
|
||||
_u.mutation.SetTargetID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableTargetID sets the "target_id" field if the given value is not nil.
|
||||
func (_u *AuditLogUpdate) SetNillableTargetID(v *string) *AuditLogUpdate {
|
||||
if v != nil {
|
||||
_u.SetTargetID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearTargetID clears the value of the "target_id" field.
|
||||
func (_u *AuditLogUpdate) ClearTargetID() *AuditLogUpdate {
|
||||
_u.mutation.ClearTargetID()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetMetadata sets the "metadata" field.
|
||||
func (_u *AuditLogUpdate) SetMetadata(v map[string]interface{}) *AuditLogUpdate {
|
||||
_u.mutation.SetMetadata(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearMetadata clears the value of the "metadata" field.
|
||||
func (_u *AuditLogUpdate) ClearMetadata() *AuditLogUpdate {
|
||||
_u.mutation.ClearMetadata()
|
||||
return _u
|
||||
}
|
||||
|
||||
// Mutation returns the AuditLogMutation object of the builder.
|
||||
func (_u *AuditLogUpdate) Mutation() *AuditLogMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (_u *AuditLogUpdate) Save(ctx context.Context) (int, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *AuditLogUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_u *AuditLogUpdate) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *AuditLogUpdate) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *AuditLogUpdate) check() error {
|
||||
if v, ok := _u.mutation.ActorID(); ok {
|
||||
if err := auditlog.ActorIDValidator(v); err != nil {
|
||||
return &ValidationError{Name: "actor_id", err: fmt.Errorf(`ent: validator failed for field "AuditLog.actor_id": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.Action(); ok {
|
||||
if err := auditlog.ActionValidator(v); err != nil {
|
||||
return &ValidationError{Name: "action", err: fmt.Errorf(`ent: validator failed for field "AuditLog.action": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *AuditLogUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(auditlog.Table, auditlog.Columns, sqlgraph.NewFieldSpec(auditlog.FieldID, field.TypeString))
|
||||
if ps := _u.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := _u.mutation.ActorID(); ok {
|
||||
_spec.SetField(auditlog.FieldActorID, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Action(); ok {
|
||||
_spec.SetField(auditlog.FieldAction, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.TargetID(); ok {
|
||||
_spec.SetField(auditlog.FieldTargetID, field.TypeString, value)
|
||||
}
|
||||
if _u.mutation.TargetIDCleared() {
|
||||
_spec.ClearField(auditlog.FieldTargetID, field.TypeString)
|
||||
}
|
||||
if value, ok := _u.mutation.Metadata(); ok {
|
||||
_spec.SetField(auditlog.FieldMetadata, field.TypeJSON, value)
|
||||
}
|
||||
if _u.mutation.MetadataCleared() {
|
||||
_spec.ClearField(auditlog.FieldMetadata, field.TypeJSON)
|
||||
}
|
||||
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{auditlog.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
// AuditLogUpdateOne is the builder for updating a single AuditLog entity.
|
||||
type AuditLogUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *AuditLogMutation
|
||||
}
|
||||
|
||||
// SetActorID sets the "actor_id" field.
|
||||
func (_u *AuditLogUpdateOne) SetActorID(v string) *AuditLogUpdateOne {
|
||||
_u.mutation.SetActorID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableActorID sets the "actor_id" field if the given value is not nil.
|
||||
func (_u *AuditLogUpdateOne) SetNillableActorID(v *string) *AuditLogUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetActorID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetAction sets the "action" field.
|
||||
func (_u *AuditLogUpdateOne) SetAction(v string) *AuditLogUpdateOne {
|
||||
_u.mutation.SetAction(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableAction sets the "action" field if the given value is not nil.
|
||||
func (_u *AuditLogUpdateOne) SetNillableAction(v *string) *AuditLogUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetAction(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetTargetID sets the "target_id" field.
|
||||
func (_u *AuditLogUpdateOne) SetTargetID(v string) *AuditLogUpdateOne {
|
||||
_u.mutation.SetTargetID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableTargetID sets the "target_id" field if the given value is not nil.
|
||||
func (_u *AuditLogUpdateOne) SetNillableTargetID(v *string) *AuditLogUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetTargetID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearTargetID clears the value of the "target_id" field.
|
||||
func (_u *AuditLogUpdateOne) ClearTargetID() *AuditLogUpdateOne {
|
||||
_u.mutation.ClearTargetID()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetMetadata sets the "metadata" field.
|
||||
func (_u *AuditLogUpdateOne) SetMetadata(v map[string]interface{}) *AuditLogUpdateOne {
|
||||
_u.mutation.SetMetadata(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearMetadata clears the value of the "metadata" field.
|
||||
func (_u *AuditLogUpdateOne) ClearMetadata() *AuditLogUpdateOne {
|
||||
_u.mutation.ClearMetadata()
|
||||
return _u
|
||||
}
|
||||
|
||||
// Mutation returns the AuditLogMutation object of the builder.
|
||||
func (_u *AuditLogUpdateOne) Mutation() *AuditLogMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the AuditLogUpdate builder.
|
||||
func (_u *AuditLogUpdateOne) Where(ps ...predicate.AuditLog) *AuditLogUpdateOne {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Select allows selecting one or more fields (columns) of the returned entity.
|
||||
// The default is selecting all fields defined in the entity schema.
|
||||
func (_u *AuditLogUpdateOne) Select(field string, fields ...string) *AuditLogUpdateOne {
|
||||
_u.fields = append([]string{field}, fields...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated AuditLog entity.
|
||||
func (_u *AuditLogUpdateOne) Save(ctx context.Context) (*AuditLog, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *AuditLogUpdateOne) SaveX(ctx context.Context) *AuditLog {
|
||||
node, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (_u *AuditLogUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *AuditLogUpdateOne) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *AuditLogUpdateOne) check() error {
|
||||
if v, ok := _u.mutation.ActorID(); ok {
|
||||
if err := auditlog.ActorIDValidator(v); err != nil {
|
||||
return &ValidationError{Name: "actor_id", err: fmt.Errorf(`ent: validator failed for field "AuditLog.actor_id": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.Action(); ok {
|
||||
if err := auditlog.ActionValidator(v); err != nil {
|
||||
return &ValidationError{Name: "action", err: fmt.Errorf(`ent: validator failed for field "AuditLog.action": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *AuditLogUpdateOne) sqlSave(ctx context.Context) (_node *AuditLog, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(auditlog.Table, auditlog.Columns, sqlgraph.NewFieldSpec(auditlog.FieldID, field.TypeString))
|
||||
id, ok := _u.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "AuditLog.id" for update`)}
|
||||
}
|
||||
_spec.Node.ID.Value = id
|
||||
if fields := _u.fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, auditlog.FieldID)
|
||||
for _, f := range fields {
|
||||
if !auditlog.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != auditlog.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := _u.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := _u.mutation.ActorID(); ok {
|
||||
_spec.SetField(auditlog.FieldActorID, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Action(); ok {
|
||||
_spec.SetField(auditlog.FieldAction, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.TargetID(); ok {
|
||||
_spec.SetField(auditlog.FieldTargetID, field.TypeString, value)
|
||||
}
|
||||
if _u.mutation.TargetIDCleared() {
|
||||
_spec.ClearField(auditlog.FieldTargetID, field.TypeString)
|
||||
}
|
||||
if value, ok := _u.mutation.Metadata(); ok {
|
||||
_spec.SetField(auditlog.FieldMetadata, field.TypeJSON, value)
|
||||
}
|
||||
if _u.mutation.MetadataCleared() {
|
||||
_spec.ClearField(auditlog.FieldMetadata, field.TypeJSON)
|
||||
}
|
||||
_node = &AuditLog{config: _u.config}
|
||||
_spec.Assign = _node.assignValues
|
||||
_spec.ScanValues = _node.scanValues
|
||||
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{auditlog.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
1182
internal/ent/client.go
Normal file
1182
internal/ent/client.go
Normal file
File diff suppressed because it is too large
Load Diff
618
internal/ent/ent.go
Normal file
618
internal/ent/ent.go
Normal file
@@ -0,0 +1,618 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"sync"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/auditlog"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/permission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/rolepermission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/user"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/userrole"
|
||||
)
|
||||
|
||||
// ent aliases to avoid import conflicts in user's code.
|
||||
type (
|
||||
Op = ent.Op
|
||||
Hook = ent.Hook
|
||||
Value = ent.Value
|
||||
Query = ent.Query
|
||||
QueryContext = ent.QueryContext
|
||||
Querier = ent.Querier
|
||||
QuerierFunc = ent.QuerierFunc
|
||||
Interceptor = ent.Interceptor
|
||||
InterceptFunc = ent.InterceptFunc
|
||||
Traverser = ent.Traverser
|
||||
TraverseFunc = ent.TraverseFunc
|
||||
Policy = ent.Policy
|
||||
Mutator = ent.Mutator
|
||||
Mutation = ent.Mutation
|
||||
MutateFunc = ent.MutateFunc
|
||||
)
|
||||
|
||||
type clientCtxKey struct{}
|
||||
|
||||
// FromContext returns a Client stored inside a context, or nil if there isn't one.
|
||||
func FromContext(ctx context.Context) *Client {
|
||||
c, _ := ctx.Value(clientCtxKey{}).(*Client)
|
||||
return c
|
||||
}
|
||||
|
||||
// NewContext returns a new context with the given Client attached.
|
||||
func NewContext(parent context.Context, c *Client) context.Context {
|
||||
return context.WithValue(parent, clientCtxKey{}, c)
|
||||
}
|
||||
|
||||
type txCtxKey struct{}
|
||||
|
||||
// TxFromContext returns a Tx stored inside a context, or nil if there isn't one.
|
||||
func TxFromContext(ctx context.Context) *Tx {
|
||||
tx, _ := ctx.Value(txCtxKey{}).(*Tx)
|
||||
return tx
|
||||
}
|
||||
|
||||
// NewTxContext returns a new context with the given Tx attached.
|
||||
func NewTxContext(parent context.Context, tx *Tx) context.Context {
|
||||
return context.WithValue(parent, txCtxKey{}, tx)
|
||||
}
|
||||
|
||||
// OrderFunc applies an ordering on the sql selector.
|
||||
// Deprecated: Use Asc/Desc functions or the package builders instead.
|
||||
type OrderFunc func(*sql.Selector)
|
||||
|
||||
var (
|
||||
initCheck sync.Once
|
||||
columnCheck sql.ColumnCheck
|
||||
)
|
||||
|
||||
// checkColumn checks if the column exists in the given table.
|
||||
func checkColumn(t, c string) error {
|
||||
initCheck.Do(func() {
|
||||
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
|
||||
auditlog.Table: auditlog.ValidColumn,
|
||||
permission.Table: permission.ValidColumn,
|
||||
role.Table: role.ValidColumn,
|
||||
rolepermission.Table: rolepermission.ValidColumn,
|
||||
user.Table: user.ValidColumn,
|
||||
userrole.Table: userrole.ValidColumn,
|
||||
})
|
||||
})
|
||||
return columnCheck(t, c)
|
||||
}
|
||||
|
||||
// Asc applies the given fields in ASC order.
|
||||
func Asc(fields ...string) func(*sql.Selector) {
|
||||
return func(s *sql.Selector) {
|
||||
for _, f := range fields {
|
||||
if err := checkColumn(s.TableName(), f); err != nil {
|
||||
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
|
||||
}
|
||||
s.OrderBy(sql.Asc(s.C(f)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Desc applies the given fields in DESC order.
|
||||
func Desc(fields ...string) func(*sql.Selector) {
|
||||
return func(s *sql.Selector) {
|
||||
for _, f := range fields {
|
||||
if err := checkColumn(s.TableName(), f); err != nil {
|
||||
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
|
||||
}
|
||||
s.OrderBy(sql.Desc(s.C(f)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// AggregateFunc applies an aggregation step on the group-by traversal/selector.
|
||||
type AggregateFunc func(*sql.Selector) string
|
||||
|
||||
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
|
||||
//
|
||||
// GroupBy(field1, field2).
|
||||
// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")).
|
||||
// Scan(ctx, &v)
|
||||
func As(fn AggregateFunc, end string) AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
return sql.As(fn(s), end)
|
||||
}
|
||||
}
|
||||
|
||||
// Count applies the "count" aggregation function on each group.
|
||||
func Count() AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
return sql.Count("*")
|
||||
}
|
||||
}
|
||||
|
||||
// Max applies the "max" aggregation function on the given field of each group.
|
||||
func Max(field string) AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
if err := checkColumn(s.TableName(), field); err != nil {
|
||||
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
|
||||
return ""
|
||||
}
|
||||
return sql.Max(s.C(field))
|
||||
}
|
||||
}
|
||||
|
||||
// Mean applies the "mean" aggregation function on the given field of each group.
|
||||
func Mean(field string) AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
if err := checkColumn(s.TableName(), field); err != nil {
|
||||
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
|
||||
return ""
|
||||
}
|
||||
return sql.Avg(s.C(field))
|
||||
}
|
||||
}
|
||||
|
||||
// Min applies the "min" aggregation function on the given field of each group.
|
||||
func Min(field string) AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
if err := checkColumn(s.TableName(), field); err != nil {
|
||||
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
|
||||
return ""
|
||||
}
|
||||
return sql.Min(s.C(field))
|
||||
}
|
||||
}
|
||||
|
||||
// Sum applies the "sum" aggregation function on the given field of each group.
|
||||
func Sum(field string) AggregateFunc {
|
||||
return func(s *sql.Selector) string {
|
||||
if err := checkColumn(s.TableName(), field); err != nil {
|
||||
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
|
||||
return ""
|
||||
}
|
||||
return sql.Sum(s.C(field))
|
||||
}
|
||||
}
|
||||
|
||||
// ValidationError returns when validating a field or edge fails.
|
||||
type ValidationError struct {
|
||||
Name string // Field or edge name.
|
||||
err error
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e *ValidationError) Error() string {
|
||||
return e.err.Error()
|
||||
}
|
||||
|
||||
// Unwrap implements the errors.Wrapper interface.
|
||||
func (e *ValidationError) Unwrap() error {
|
||||
return e.err
|
||||
}
|
||||
|
||||
// IsValidationError returns a boolean indicating whether the error is a validation error.
|
||||
func IsValidationError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var e *ValidationError
|
||||
return errors.As(err, &e)
|
||||
}
|
||||
|
||||
// NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
|
||||
type NotFoundError struct {
|
||||
label string
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e *NotFoundError) Error() string {
|
||||
return "ent: " + e.label + " not found"
|
||||
}
|
||||
|
||||
// IsNotFound returns a boolean indicating whether the error is a not found error.
|
||||
func IsNotFound(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var e *NotFoundError
|
||||
return errors.As(err, &e)
|
||||
}
|
||||
|
||||
// MaskNotFound masks not found error.
|
||||
func MaskNotFound(err error) error {
|
||||
if IsNotFound(err) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
|
||||
type NotSingularError struct {
|
||||
label string
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e *NotSingularError) Error() string {
|
||||
return "ent: " + e.label + " not singular"
|
||||
}
|
||||
|
||||
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
|
||||
func IsNotSingular(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var e *NotSingularError
|
||||
return errors.As(err, &e)
|
||||
}
|
||||
|
||||
// NotLoadedError returns when trying to get a node that was not loaded by the query.
|
||||
type NotLoadedError struct {
|
||||
edge string
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e *NotLoadedError) Error() string {
|
||||
return "ent: " + e.edge + " edge was not loaded"
|
||||
}
|
||||
|
||||
// IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
|
||||
func IsNotLoaded(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var e *NotLoadedError
|
||||
return errors.As(err, &e)
|
||||
}
|
||||
|
||||
// ConstraintError returns when trying to create/update one or more entities and
|
||||
// one or more of their constraints failed. For example, violation of edge or
|
||||
// field uniqueness.
|
||||
type ConstraintError struct {
|
||||
msg string
|
||||
wrap error
|
||||
}
|
||||
|
||||
// Error implements the error interface.
|
||||
func (e ConstraintError) Error() string {
|
||||
return "ent: constraint failed: " + e.msg
|
||||
}
|
||||
|
||||
// Unwrap implements the errors.Wrapper interface.
|
||||
func (e *ConstraintError) Unwrap() error {
|
||||
return e.wrap
|
||||
}
|
||||
|
||||
// IsConstraintError returns a boolean indicating whether the error is a constraint failure.
|
||||
func IsConstraintError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var e *ConstraintError
|
||||
return errors.As(err, &e)
|
||||
}
|
||||
|
||||
// selector embedded by the different Select/GroupBy builders.
|
||||
type selector struct {
|
||||
label string
|
||||
flds *[]string
|
||||
fns []AggregateFunc
|
||||
scan func(context.Context, any) error
|
||||
}
|
||||
|
||||
// ScanX is like Scan, but panics if an error occurs.
|
||||
func (s *selector) ScanX(ctx context.Context, v any) {
|
||||
if err := s.scan(ctx, v); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
|
||||
func (s *selector) Strings(ctx context.Context) ([]string, error) {
|
||||
if len(*s.flds) > 1 {
|
||||
return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []string
|
||||
if err := s.scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// StringsX is like Strings, but panics if an error occurs.
|
||||
func (s *selector) StringsX(ctx context.Context) []string {
|
||||
v, err := s.Strings(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// String returns a single string from a selector. It is only allowed when selecting one field.
|
||||
func (s *selector) String(ctx context.Context) (_ string, err error) {
|
||||
var v []string
|
||||
if v, err = s.Strings(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(v) {
|
||||
case 1:
|
||||
return v[0], nil
|
||||
case 0:
|
||||
err = &NotFoundError{s.label}
|
||||
default:
|
||||
err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// StringX is like String, but panics if an error occurs.
|
||||
func (s *selector) StringX(ctx context.Context) string {
|
||||
v, err := s.String(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
|
||||
func (s *selector) Ints(ctx context.Context) ([]int, error) {
|
||||
if len(*s.flds) > 1 {
|
||||
return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []int
|
||||
if err := s.scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// IntsX is like Ints, but panics if an error occurs.
|
||||
func (s *selector) IntsX(ctx context.Context) []int {
|
||||
v, err := s.Ints(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Int returns a single int from a selector. It is only allowed when selecting one field.
|
||||
func (s *selector) Int(ctx context.Context) (_ int, err error) {
|
||||
var v []int
|
||||
if v, err = s.Ints(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(v) {
|
||||
case 1:
|
||||
return v[0], nil
|
||||
case 0:
|
||||
err = &NotFoundError{s.label}
|
||||
default:
|
||||
err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// IntX is like Int, but panics if an error occurs.
|
||||
func (s *selector) IntX(ctx context.Context) int {
|
||||
v, err := s.Int(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
|
||||
func (s *selector) Float64s(ctx context.Context) ([]float64, error) {
|
||||
if len(*s.flds) > 1 {
|
||||
return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []float64
|
||||
if err := s.scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// Float64sX is like Float64s, but panics if an error occurs.
|
||||
func (s *selector) Float64sX(ctx context.Context) []float64 {
|
||||
v, err := s.Float64s(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
|
||||
func (s *selector) Float64(ctx context.Context) (_ float64, err error) {
|
||||
var v []float64
|
||||
if v, err = s.Float64s(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(v) {
|
||||
case 1:
|
||||
return v[0], nil
|
||||
case 0:
|
||||
err = &NotFoundError{s.label}
|
||||
default:
|
||||
err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Float64X is like Float64, but panics if an error occurs.
|
||||
func (s *selector) Float64X(ctx context.Context) float64 {
|
||||
v, err := s.Float64(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
|
||||
func (s *selector) Bools(ctx context.Context) ([]bool, error) {
|
||||
if len(*s.flds) > 1 {
|
||||
return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field")
|
||||
}
|
||||
var v []bool
|
||||
if err := s.scan(ctx, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// BoolsX is like Bools, but panics if an error occurs.
|
||||
func (s *selector) BoolsX(ctx context.Context) []bool {
|
||||
v, err := s.Bools(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
|
||||
func (s *selector) Bool(ctx context.Context) (_ bool, err error) {
|
||||
var v []bool
|
||||
if v, err = s.Bools(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(v) {
|
||||
case 1:
|
||||
return v[0], nil
|
||||
case 0:
|
||||
err = &NotFoundError{s.label}
|
||||
default:
|
||||
err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// BoolX is like Bool, but panics if an error occurs.
|
||||
func (s *selector) BoolX(ctx context.Context) bool {
|
||||
v, err := s.Bool(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// withHooks invokes the builder operation with the given hooks, if any.
|
||||
func withHooks[V Value, M any, PM interface {
|
||||
*M
|
||||
Mutation
|
||||
}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) {
|
||||
if len(hooks) == 0 {
|
||||
return exec(ctx)
|
||||
}
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutationT, ok := any(m).(PM)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
// Set the mutation to the builder.
|
||||
*mutation = *mutationT
|
||||
return exec(ctx)
|
||||
})
|
||||
for i := len(hooks) - 1; i >= 0; i-- {
|
||||
if hooks[i] == nil {
|
||||
return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
|
||||
}
|
||||
mut = hooks[i](mut)
|
||||
}
|
||||
v, err := mut.Mutate(ctx, mutation)
|
||||
if err != nil {
|
||||
return value, err
|
||||
}
|
||||
nv, ok := v.(V)
|
||||
if !ok {
|
||||
return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation)
|
||||
}
|
||||
return nv, nil
|
||||
}
|
||||
|
||||
// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist.
|
||||
func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context {
|
||||
if ent.QueryFromContext(ctx) == nil {
|
||||
qc.Op = op
|
||||
ctx = ent.NewQueryContext(ctx, qc)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
func querierAll[V Value, Q interface {
|
||||
sqlAll(context.Context, ...queryHook) (V, error)
|
||||
}]() Querier {
|
||||
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
|
||||
query, ok := q.(Q)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected query type %T", q)
|
||||
}
|
||||
return query.sqlAll(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
func querierCount[Q interface {
|
||||
sqlCount(context.Context) (int, error)
|
||||
}]() Querier {
|
||||
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
|
||||
query, ok := q.(Q)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected query type %T", q)
|
||||
}
|
||||
return query.sqlCount(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) {
|
||||
for i := len(inters) - 1; i >= 0; i-- {
|
||||
qr = inters[i].Intercept(qr)
|
||||
}
|
||||
rv, err := qr.Query(ctx, q)
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
vt, ok := rv.(V)
|
||||
if !ok {
|
||||
return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v)
|
||||
}
|
||||
return vt, nil
|
||||
}
|
||||
|
||||
func scanWithInterceptors[Q1 ent.Query, Q2 interface {
|
||||
sqlScan(context.Context, Q1, any) error
|
||||
}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error {
|
||||
rv := reflect.ValueOf(v)
|
||||
var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
|
||||
query, ok := q.(Q1)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected query type %T", q)
|
||||
}
|
||||
if err := selectOrGroup.sqlScan(ctx, query, v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() {
|
||||
return rv.Elem().Interface(), nil
|
||||
}
|
||||
return v, nil
|
||||
})
|
||||
for i := len(inters) - 1; i >= 0; i-- {
|
||||
qr = inters[i].Intercept(qr)
|
||||
}
|
||||
vv, err := qr.Query(ctx, rootQuery)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch rv2 := reflect.ValueOf(vv); {
|
||||
case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer:
|
||||
case rv.Type() == rv2.Type():
|
||||
rv.Elem().Set(rv2.Elem())
|
||||
case rv.Elem().Type() == rv2.Type():
|
||||
rv.Elem().Set(rv2)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// queryHook describes an internal hook for the different sqlAll methods.
|
||||
type queryHook func(context.Context, *sqlgraph.QuerySpec)
|
||||
84
internal/ent/enttest/enttest.go
Normal file
84
internal/ent/enttest/enttest.go
Normal file
@@ -0,0 +1,84 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package enttest
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent"
|
||||
// required by schema hooks.
|
||||
_ "git.dcentral.systems/toolz/goplt/internal/ent/runtime"
|
||||
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/migrate"
|
||||
)
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
259
internal/ent/hook/hook.go
Normal file
259
internal/ent/hook/hook.go
Normal file
@@ -0,0 +1,259 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package hook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent"
|
||||
)
|
||||
|
||||
// The AuditLogFunc type is an adapter to allow the use of ordinary
|
||||
// function as AuditLog mutator.
|
||||
type AuditLogFunc func(context.Context, *ent.AuditLogMutation) (ent.Value, error)
|
||||
|
||||
// Mutate calls f(ctx, m).
|
||||
func (f AuditLogFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
|
||||
if mv, ok := m.(*ent.AuditLogMutation); ok {
|
||||
return f(ctx, mv)
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.AuditLogMutation", m)
|
||||
}
|
||||
|
||||
// The PermissionFunc type is an adapter to allow the use of ordinary
|
||||
// function as Permission mutator.
|
||||
type PermissionFunc func(context.Context, *ent.PermissionMutation) (ent.Value, error)
|
||||
|
||||
// Mutate calls f(ctx, m).
|
||||
func (f PermissionFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
|
||||
if mv, ok := m.(*ent.PermissionMutation); ok {
|
||||
return f(ctx, mv)
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.PermissionMutation", m)
|
||||
}
|
||||
|
||||
// The RoleFunc type is an adapter to allow the use of ordinary
|
||||
// function as Role mutator.
|
||||
type RoleFunc func(context.Context, *ent.RoleMutation) (ent.Value, error)
|
||||
|
||||
// Mutate calls f(ctx, m).
|
||||
func (f RoleFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
|
||||
if mv, ok := m.(*ent.RoleMutation); ok {
|
||||
return f(ctx, mv)
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.RoleMutation", m)
|
||||
}
|
||||
|
||||
// The RolePermissionFunc type is an adapter to allow the use of ordinary
|
||||
// function as RolePermission mutator.
|
||||
type RolePermissionFunc func(context.Context, *ent.RolePermissionMutation) (ent.Value, error)
|
||||
|
||||
// Mutate calls f(ctx, m).
|
||||
func (f RolePermissionFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
|
||||
if mv, ok := m.(*ent.RolePermissionMutation); ok {
|
||||
return f(ctx, mv)
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.RolePermissionMutation", 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)
|
||||
}
|
||||
|
||||
// The UserRoleFunc type is an adapter to allow the use of ordinary
|
||||
// function as UserRole mutator.
|
||||
type UserRoleFunc func(context.Context, *ent.UserRoleMutation) (ent.Value, error)
|
||||
|
||||
// Mutate calls f(ctx, m).
|
||||
func (f UserRoleFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
|
||||
if mv, ok := m.(*ent.UserRoleMutation); ok {
|
||||
return f(ctx, mv)
|
||||
}
|
||||
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserRoleMutation", 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
internal/ent/migrate/migrate.go
Normal file
64
internal/ent/migrate/migrate.go
Normal 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...)
|
||||
}
|
||||
187
internal/ent/migrate/schema.go
Normal file
187
internal/ent/migrate/schema.go
Normal file
@@ -0,0 +1,187 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package migrate
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql/schema"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
var (
|
||||
// AuditLogsColumns holds the columns for the "audit_logs" table.
|
||||
AuditLogsColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeString, Unique: true},
|
||||
{Name: "actor_id", Type: field.TypeString},
|
||||
{Name: "action", Type: field.TypeString},
|
||||
{Name: "target_id", Type: field.TypeString, Nullable: true},
|
||||
{Name: "metadata", Type: field.TypeJSON, Nullable: true},
|
||||
{Name: "timestamp", Type: field.TypeTime},
|
||||
}
|
||||
// AuditLogsTable holds the schema information for the "audit_logs" table.
|
||||
AuditLogsTable = &schema.Table{
|
||||
Name: "audit_logs",
|
||||
Columns: AuditLogsColumns,
|
||||
PrimaryKey: []*schema.Column{AuditLogsColumns[0]},
|
||||
Indexes: []*schema.Index{
|
||||
{
|
||||
Name: "auditlog_actor_id",
|
||||
Unique: false,
|
||||
Columns: []*schema.Column{AuditLogsColumns[1]},
|
||||
},
|
||||
{
|
||||
Name: "auditlog_target_id",
|
||||
Unique: false,
|
||||
Columns: []*schema.Column{AuditLogsColumns[3]},
|
||||
},
|
||||
{
|
||||
Name: "auditlog_timestamp",
|
||||
Unique: false,
|
||||
Columns: []*schema.Column{AuditLogsColumns[5]},
|
||||
},
|
||||
{
|
||||
Name: "auditlog_action",
|
||||
Unique: false,
|
||||
Columns: []*schema.Column{AuditLogsColumns[2]},
|
||||
},
|
||||
},
|
||||
}
|
||||
// PermissionsColumns holds the columns for the "permissions" table.
|
||||
PermissionsColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeString, Unique: true},
|
||||
{Name: "name", Type: field.TypeString, Unique: true},
|
||||
}
|
||||
// PermissionsTable holds the schema information for the "permissions" table.
|
||||
PermissionsTable = &schema.Table{
|
||||
Name: "permissions",
|
||||
Columns: PermissionsColumns,
|
||||
PrimaryKey: []*schema.Column{PermissionsColumns[0]},
|
||||
}
|
||||
// RolesColumns holds the columns for the "roles" table.
|
||||
RolesColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeString, Unique: true},
|
||||
{Name: "name", Type: field.TypeString, Unique: true},
|
||||
{Name: "description", Type: field.TypeString, Nullable: true},
|
||||
{Name: "created_at", Type: field.TypeTime},
|
||||
}
|
||||
// RolesTable holds the schema information for the "roles" table.
|
||||
RolesTable = &schema.Table{
|
||||
Name: "roles",
|
||||
Columns: RolesColumns,
|
||||
PrimaryKey: []*schema.Column{RolesColumns[0]},
|
||||
}
|
||||
// RolePermissionsColumns holds the columns for the "role_permissions" table.
|
||||
RolePermissionsColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeInt, Increment: true},
|
||||
{Name: "permission_role_permissions", Type: field.TypeString, Nullable: true},
|
||||
{Name: "role_role_permissions", Type: field.TypeString, Nullable: true},
|
||||
{Name: "role_id", Type: field.TypeString},
|
||||
{Name: "permission_id", Type: field.TypeString},
|
||||
}
|
||||
// RolePermissionsTable holds the schema information for the "role_permissions" table.
|
||||
RolePermissionsTable = &schema.Table{
|
||||
Name: "role_permissions",
|
||||
Columns: RolePermissionsColumns,
|
||||
PrimaryKey: []*schema.Column{RolePermissionsColumns[0]},
|
||||
ForeignKeys: []*schema.ForeignKey{
|
||||
{
|
||||
Symbol: "role_permissions_permissions_role_permissions",
|
||||
Columns: []*schema.Column{RolePermissionsColumns[1]},
|
||||
RefColumns: []*schema.Column{PermissionsColumns[0]},
|
||||
OnDelete: schema.SetNull,
|
||||
},
|
||||
{
|
||||
Symbol: "role_permissions_roles_role_permissions",
|
||||
Columns: []*schema.Column{RolePermissionsColumns[2]},
|
||||
RefColumns: []*schema.Column{RolesColumns[0]},
|
||||
OnDelete: schema.SetNull,
|
||||
},
|
||||
{
|
||||
Symbol: "role_permissions_roles_role",
|
||||
Columns: []*schema.Column{RolePermissionsColumns[3]},
|
||||
RefColumns: []*schema.Column{RolesColumns[0]},
|
||||
OnDelete: schema.NoAction,
|
||||
},
|
||||
{
|
||||
Symbol: "role_permissions_permissions_permission",
|
||||
Columns: []*schema.Column{RolePermissionsColumns[4]},
|
||||
RefColumns: []*schema.Column{PermissionsColumns[0]},
|
||||
OnDelete: schema.NoAction,
|
||||
},
|
||||
},
|
||||
}
|
||||
// UsersColumns holds the columns for the "users" table.
|
||||
UsersColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeString, Unique: true},
|
||||
{Name: "email", Type: field.TypeString, Unique: true},
|
||||
{Name: "password_hash", Type: field.TypeString},
|
||||
{Name: "verified", Type: field.TypeBool, Default: false},
|
||||
{Name: "created_at", Type: field.TypeTime},
|
||||
{Name: "updated_at", Type: field.TypeTime},
|
||||
}
|
||||
// UsersTable holds the schema information for the "users" table.
|
||||
UsersTable = &schema.Table{
|
||||
Name: "users",
|
||||
Columns: UsersColumns,
|
||||
PrimaryKey: []*schema.Column{UsersColumns[0]},
|
||||
}
|
||||
// UserRolesColumns holds the columns for the "user_roles" table.
|
||||
UserRolesColumns = []*schema.Column{
|
||||
{Name: "id", Type: field.TypeInt, Increment: true},
|
||||
{Name: "role_user_roles", Type: field.TypeString, Nullable: true},
|
||||
{Name: "user_user_roles", Type: field.TypeString, Nullable: true},
|
||||
{Name: "user_id", Type: field.TypeString},
|
||||
{Name: "role_id", Type: field.TypeString},
|
||||
}
|
||||
// UserRolesTable holds the schema information for the "user_roles" table.
|
||||
UserRolesTable = &schema.Table{
|
||||
Name: "user_roles",
|
||||
Columns: UserRolesColumns,
|
||||
PrimaryKey: []*schema.Column{UserRolesColumns[0]},
|
||||
ForeignKeys: []*schema.ForeignKey{
|
||||
{
|
||||
Symbol: "user_roles_roles_user_roles",
|
||||
Columns: []*schema.Column{UserRolesColumns[1]},
|
||||
RefColumns: []*schema.Column{RolesColumns[0]},
|
||||
OnDelete: schema.SetNull,
|
||||
},
|
||||
{
|
||||
Symbol: "user_roles_users_user_roles",
|
||||
Columns: []*schema.Column{UserRolesColumns[2]},
|
||||
RefColumns: []*schema.Column{UsersColumns[0]},
|
||||
OnDelete: schema.SetNull,
|
||||
},
|
||||
{
|
||||
Symbol: "user_roles_users_user",
|
||||
Columns: []*schema.Column{UserRolesColumns[3]},
|
||||
RefColumns: []*schema.Column{UsersColumns[0]},
|
||||
OnDelete: schema.NoAction,
|
||||
},
|
||||
{
|
||||
Symbol: "user_roles_roles_role",
|
||||
Columns: []*schema.Column{UserRolesColumns[4]},
|
||||
RefColumns: []*schema.Column{RolesColumns[0]},
|
||||
OnDelete: schema.NoAction,
|
||||
},
|
||||
},
|
||||
}
|
||||
// Tables holds all the tables in the schema.
|
||||
Tables = []*schema.Table{
|
||||
AuditLogsTable,
|
||||
PermissionsTable,
|
||||
RolesTable,
|
||||
RolePermissionsTable,
|
||||
UsersTable,
|
||||
UserRolesTable,
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
RolePermissionsTable.ForeignKeys[0].RefTable = PermissionsTable
|
||||
RolePermissionsTable.ForeignKeys[1].RefTable = RolesTable
|
||||
RolePermissionsTable.ForeignKeys[2].RefTable = RolesTable
|
||||
RolePermissionsTable.ForeignKeys[3].RefTable = PermissionsTable
|
||||
UserRolesTable.ForeignKeys[0].RefTable = RolesTable
|
||||
UserRolesTable.ForeignKeys[1].RefTable = UsersTable
|
||||
UserRolesTable.ForeignKeys[2].RefTable = UsersTable
|
||||
UserRolesTable.ForeignKeys[3].RefTable = RolesTable
|
||||
}
|
||||
3291
internal/ent/mutation.go
Normal file
3291
internal/ent/mutation.go
Normal file
File diff suppressed because it is too large
Load Diff
127
internal/ent/permission.go
Normal file
127
internal/ent/permission.go
Normal file
@@ -0,0 +1,127 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/permission"
|
||||
)
|
||||
|
||||
// Permission is the model entity for the Permission schema.
|
||||
type Permission struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID string `json:"id,omitempty"`
|
||||
// Format: module.resource.action
|
||||
Name string `json:"name,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
// The values are being populated by the PermissionQuery when eager-loading is set.
|
||||
Edges PermissionEdges `json:"edges"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// PermissionEdges holds the relations/edges for other nodes in the graph.
|
||||
type PermissionEdges struct {
|
||||
// RolePermissions holds the value of the role_permissions edge.
|
||||
RolePermissions []*RolePermission `json:"role_permissions,omitempty"`
|
||||
// loadedTypes holds the information for reporting if a
|
||||
// type was loaded (or requested) in eager-loading or not.
|
||||
loadedTypes [1]bool
|
||||
}
|
||||
|
||||
// RolePermissionsOrErr returns the RolePermissions value or an error if the edge
|
||||
// was not loaded in eager-loading.
|
||||
func (e PermissionEdges) RolePermissionsOrErr() ([]*RolePermission, error) {
|
||||
if e.loadedTypes[0] {
|
||||
return e.RolePermissions, nil
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "role_permissions"}
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*Permission) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case permission.FieldID, permission.FieldName:
|
||||
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 Permission fields.
|
||||
func (_m *Permission) 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 permission.FieldID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ID = value.String
|
||||
}
|
||||
case permission.FieldName:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field name", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Name = value.String
|
||||
}
|
||||
default:
|
||||
_m.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value returns the ent.Value that was dynamically selected and assigned to the Permission.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (_m *Permission) Value(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// QueryRolePermissions queries the "role_permissions" edge of the Permission entity.
|
||||
func (_m *Permission) QueryRolePermissions() *RolePermissionQuery {
|
||||
return NewPermissionClient(_m.config).QueryRolePermissions(_m)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this Permission.
|
||||
// Note that you need to call Permission.Unwrap() before calling this method if this Permission
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (_m *Permission) Update() *PermissionUpdateOne {
|
||||
return NewPermissionClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the Permission entity that was returned from a transaction after it was closed,
|
||||
// so that all future queries will be executed through the driver which created the transaction.
|
||||
func (_m *Permission) Unwrap() *Permission {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: Permission is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *Permission) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("Permission(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
builder.WriteString("name=")
|
||||
builder.WriteString(_m.Name)
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// Permissions is a parsable slice of Permission.
|
||||
type Permissions []*Permission
|
||||
83
internal/ent/permission/permission.go
Normal file
83
internal/ent/permission/permission.go
Normal file
@@ -0,0 +1,83 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package permission
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the permission type in the database.
|
||||
Label = "permission"
|
||||
// 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"
|
||||
// EdgeRolePermissions holds the string denoting the role_permissions edge name in mutations.
|
||||
EdgeRolePermissions = "role_permissions"
|
||||
// Table holds the table name of the permission in the database.
|
||||
Table = "permissions"
|
||||
// RolePermissionsTable is the table that holds the role_permissions relation/edge.
|
||||
RolePermissionsTable = "role_permissions"
|
||||
// RolePermissionsInverseTable is the table name for the RolePermission entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "rolepermission" package.
|
||||
RolePermissionsInverseTable = "role_permissions"
|
||||
// RolePermissionsColumn is the table column denoting the role_permissions relation/edge.
|
||||
RolePermissionsColumn = "permission_role_permissions"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for permission fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldName,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
if column == Columns[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var (
|
||||
// NameValidator is a validator for the "name" field. It is called by the builders before save.
|
||||
NameValidator func(string) error
|
||||
)
|
||||
|
||||
// OrderOption defines the ordering options for the Permission 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()
|
||||
}
|
||||
|
||||
// ByRolePermissionsCount orders the results by role_permissions count.
|
||||
func ByRolePermissionsCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborsCount(s, newRolePermissionsStep(), opts...)
|
||||
}
|
||||
}
|
||||
|
||||
// ByRolePermissions orders the results by role_permissions terms.
|
||||
func ByRolePermissions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newRolePermissionsStep(), append([]sql.OrderTerm{term}, terms...)...)
|
||||
}
|
||||
}
|
||||
func newRolePermissionsStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(RolePermissionsInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, RolePermissionsTable, RolePermissionsColumn),
|
||||
)
|
||||
}
|
||||
172
internal/ent/permission/where.go
Normal file
172
internal/ent/permission/where.go
Normal file
@@ -0,0 +1,172 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package permission
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEqualFold applies the EqualFold predicate on the ID field.
|
||||
func IDEqualFold(id string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldEqualFold(FieldID, id))
|
||||
}
|
||||
|
||||
// IDContainsFold applies the ContainsFold predicate on the ID field.
|
||||
func IDContainsFold(id string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldContainsFold(FieldID, id))
|
||||
}
|
||||
|
||||
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
|
||||
func Name(v string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldEQ(FieldName, v))
|
||||
}
|
||||
|
||||
// NameEQ applies the EQ predicate on the "name" field.
|
||||
func NameEQ(v string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldEQ(FieldName, v))
|
||||
}
|
||||
|
||||
// NameNEQ applies the NEQ predicate on the "name" field.
|
||||
func NameNEQ(v string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldNEQ(FieldName, v))
|
||||
}
|
||||
|
||||
// NameIn applies the In predicate on the "name" field.
|
||||
func NameIn(vs ...string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldIn(FieldName, vs...))
|
||||
}
|
||||
|
||||
// NameNotIn applies the NotIn predicate on the "name" field.
|
||||
func NameNotIn(vs ...string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldNotIn(FieldName, vs...))
|
||||
}
|
||||
|
||||
// NameGT applies the GT predicate on the "name" field.
|
||||
func NameGT(v string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldGT(FieldName, v))
|
||||
}
|
||||
|
||||
// NameGTE applies the GTE predicate on the "name" field.
|
||||
func NameGTE(v string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldGTE(FieldName, v))
|
||||
}
|
||||
|
||||
// NameLT applies the LT predicate on the "name" field.
|
||||
func NameLT(v string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldLT(FieldName, v))
|
||||
}
|
||||
|
||||
// NameLTE applies the LTE predicate on the "name" field.
|
||||
func NameLTE(v string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldLTE(FieldName, v))
|
||||
}
|
||||
|
||||
// NameContains applies the Contains predicate on the "name" field.
|
||||
func NameContains(v string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldContains(FieldName, v))
|
||||
}
|
||||
|
||||
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
|
||||
func NameHasPrefix(v string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldHasPrefix(FieldName, v))
|
||||
}
|
||||
|
||||
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
|
||||
func NameHasSuffix(v string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldHasSuffix(FieldName, v))
|
||||
}
|
||||
|
||||
// NameEqualFold applies the EqualFold predicate on the "name" field.
|
||||
func NameEqualFold(v string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldEqualFold(FieldName, v))
|
||||
}
|
||||
|
||||
// NameContainsFold applies the ContainsFold predicate on the "name" field.
|
||||
func NameContainsFold(v string) predicate.Permission {
|
||||
return predicate.Permission(sql.FieldContainsFold(FieldName, v))
|
||||
}
|
||||
|
||||
// HasRolePermissions applies the HasEdge predicate on the "role_permissions" edge.
|
||||
func HasRolePermissions() predicate.Permission {
|
||||
return predicate.Permission(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, RolePermissionsTable, RolePermissionsColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasRolePermissionsWith applies the HasEdge predicate on the "role_permissions" edge with a given conditions (other predicates).
|
||||
func HasRolePermissionsWith(preds ...predicate.RolePermission) predicate.Permission {
|
||||
return predicate.Permission(func(s *sql.Selector) {
|
||||
step := newRolePermissionsStep()
|
||||
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.Permission) predicate.Permission {
|
||||
return predicate.Permission(sql.AndPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.Permission) predicate.Permission {
|
||||
return predicate.Permission(sql.OrPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.Permission) predicate.Permission {
|
||||
return predicate.Permission(sql.NotPredicates(p))
|
||||
}
|
||||
231
internal/ent/permission_create.go
Normal file
231
internal/ent/permission_create.go
Normal file
@@ -0,0 +1,231 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/permission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/rolepermission"
|
||||
)
|
||||
|
||||
// PermissionCreate is the builder for creating a Permission entity.
|
||||
type PermissionCreate struct {
|
||||
config
|
||||
mutation *PermissionMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetName sets the "name" field.
|
||||
func (_c *PermissionCreate) SetName(v string) *PermissionCreate {
|
||||
_c.mutation.SetName(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetID sets the "id" field.
|
||||
func (_c *PermissionCreate) SetID(v string) *PermissionCreate {
|
||||
_c.mutation.SetID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// AddRolePermissionIDs adds the "role_permissions" edge to the RolePermission entity by IDs.
|
||||
func (_c *PermissionCreate) AddRolePermissionIDs(ids ...int) *PermissionCreate {
|
||||
_c.mutation.AddRolePermissionIDs(ids...)
|
||||
return _c
|
||||
}
|
||||
|
||||
// AddRolePermissions adds the "role_permissions" edges to the RolePermission entity.
|
||||
func (_c *PermissionCreate) AddRolePermissions(v ...*RolePermission) *PermissionCreate {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _c.AddRolePermissionIDs(ids...)
|
||||
}
|
||||
|
||||
// Mutation returns the PermissionMutation object of the builder.
|
||||
func (_c *PermissionCreate) Mutation() *PermissionMutation {
|
||||
return _c.mutation
|
||||
}
|
||||
|
||||
// Save creates the Permission in the database.
|
||||
func (_c *PermissionCreate) Save(ctx context.Context) (*Permission, error) {
|
||||
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (_c *PermissionCreate) SaveX(ctx context.Context) *Permission {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *PermissionCreate) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *PermissionCreate) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_c *PermissionCreate) check() error {
|
||||
if _, ok := _c.mutation.Name(); !ok {
|
||||
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Permission.name"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.Name(); ok {
|
||||
if err := permission.NameValidator(v); err != nil {
|
||||
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Permission.name": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_c *PermissionCreate) sqlSave(ctx context.Context) (*Permission, error) {
|
||||
if err := _c.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := _c.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if _spec.ID.Value != nil {
|
||||
if id, ok := _spec.ID.Value.(string); ok {
|
||||
_node.ID = id
|
||||
} else {
|
||||
return nil, fmt.Errorf("unexpected Permission.ID type: %T", _spec.ID.Value)
|
||||
}
|
||||
}
|
||||
_c.mutation.id = &_node.ID
|
||||
_c.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (_c *PermissionCreate) createSpec() (*Permission, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &Permission{config: _c.config}
|
||||
_spec = sqlgraph.NewCreateSpec(permission.Table, sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString))
|
||||
)
|
||||
if id, ok := _c.mutation.ID(); ok {
|
||||
_node.ID = id
|
||||
_spec.ID.Value = id
|
||||
}
|
||||
if value, ok := _c.mutation.Name(); ok {
|
||||
_spec.SetField(permission.FieldName, field.TypeString, value)
|
||||
_node.Name = value
|
||||
}
|
||||
if nodes := _c.mutation.RolePermissionsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: permission.RolePermissionsTable,
|
||||
Columns: []string{permission.RolePermissionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// PermissionCreateBulk is the builder for creating many Permission entities in bulk.
|
||||
type PermissionCreateBulk struct {
|
||||
config
|
||||
err error
|
||||
builders []*PermissionCreate
|
||||
}
|
||||
|
||||
// Save creates the Permission entities in the database.
|
||||
func (_c *PermissionCreateBulk) Save(ctx context.Context) ([]*Permission, error) {
|
||||
if _c.err != nil {
|
||||
return nil, _c.err
|
||||
}
|
||||
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
|
||||
nodes := make([]*Permission, len(_c.builders))
|
||||
mutators := make([]Mutator, len(_c.builders))
|
||||
for i := range _c.builders {
|
||||
func(i int, root context.Context) {
|
||||
builder := _c.builders[i]
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*PermissionMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err := builder.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
builder.mutation = mutation
|
||||
var err error
|
||||
nodes[i], specs[i] = builder.createSpec()
|
||||
if i < len(mutators)-1 {
|
||||
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
|
||||
} else {
|
||||
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
|
||||
// Invoke the actual operation on the latest mutation in the chain.
|
||||
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &nodes[i].ID
|
||||
mutation.done = true
|
||||
return nodes[i], nil
|
||||
})
|
||||
for i := len(builder.hooks) - 1; i >= 0; i-- {
|
||||
mut = builder.hooks[i](mut)
|
||||
}
|
||||
mutators[i] = mut
|
||||
}(i, ctx)
|
||||
}
|
||||
if len(mutators) > 0 {
|
||||
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_c *PermissionCreateBulk) SaveX(ctx context.Context) []*Permission {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *PermissionCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *PermissionCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
88
internal/ent/permission_delete.go
Normal file
88
internal/ent/permission_delete.go
Normal file
@@ -0,0 +1,88 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/permission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
)
|
||||
|
||||
// PermissionDelete is the builder for deleting a Permission entity.
|
||||
type PermissionDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *PermissionMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the PermissionDelete builder.
|
||||
func (_d *PermissionDelete) Where(ps ...predicate.Permission) *PermissionDelete {
|
||||
_d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (_d *PermissionDelete) Exec(ctx context.Context) (int, error) {
|
||||
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *PermissionDelete) ExecX(ctx context.Context) int {
|
||||
n, err := _d.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (_d *PermissionDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(permission.Table, sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString))
|
||||
if ps := _d.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
|
||||
if err != nil && sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
_d.mutation.done = true
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// PermissionDeleteOne is the builder for deleting a single Permission entity.
|
||||
type PermissionDeleteOne struct {
|
||||
_d *PermissionDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the PermissionDelete builder.
|
||||
func (_d *PermissionDeleteOne) Where(ps ...predicate.Permission) *PermissionDeleteOne {
|
||||
_d._d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (_d *PermissionDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := _d._d.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{permission.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *PermissionDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := _d.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
607
internal/ent/permission_query.go
Normal file
607
internal/ent/permission_query.go
Normal file
@@ -0,0 +1,607 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/permission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/rolepermission"
|
||||
)
|
||||
|
||||
// PermissionQuery is the builder for querying Permission entities.
|
||||
type PermissionQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []permission.OrderOption
|
||||
inters []Interceptor
|
||||
predicates []predicate.Permission
|
||||
withRolePermissions *RolePermissionQuery
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the PermissionQuery builder.
|
||||
func (_q *PermissionQuery) Where(ps ...predicate.Permission) *PermissionQuery {
|
||||
_q.predicates = append(_q.predicates, ps...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
func (_q *PermissionQuery) Limit(limit int) *PermissionQuery {
|
||||
_q.ctx.Limit = &limit
|
||||
return _q
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
func (_q *PermissionQuery) Offset(offset int) *PermissionQuery {
|
||||
_q.ctx.Offset = &offset
|
||||
return _q
|
||||
}
|
||||
|
||||
// Unique configures the query builder to filter duplicate records on query.
|
||||
// By default, unique is set to true, and can be disabled using this method.
|
||||
func (_q *PermissionQuery) Unique(unique bool) *PermissionQuery {
|
||||
_q.ctx.Unique = &unique
|
||||
return _q
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
func (_q *PermissionQuery) Order(o ...permission.OrderOption) *PermissionQuery {
|
||||
_q.order = append(_q.order, o...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// QueryRolePermissions chains the current query on the "role_permissions" edge.
|
||||
func (_q *PermissionQuery) QueryRolePermissions() *RolePermissionQuery {
|
||||
query := (&RolePermissionClient{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(permission.Table, permission.FieldID, selector),
|
||||
sqlgraph.To(rolepermission.Table, rolepermission.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, permission.RolePermissionsTable, permission.RolePermissionsColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// First returns the first Permission entity from the query.
|
||||
// Returns a *NotFoundError when no Permission was found.
|
||||
func (_q *PermissionQuery) First(ctx context.Context) (*Permission, error) {
|
||||
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nil, &NotFoundError{permission.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (_q *PermissionQuery) FirstX(ctx context.Context) *Permission {
|
||||
node, err := _q.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first Permission ID from the query.
|
||||
// Returns a *NotFoundError when no Permission ID was found.
|
||||
func (_q *PermissionQuery) FirstID(ctx context.Context) (id string, err error) {
|
||||
var ids []string
|
||||
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &NotFoundError{permission.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (_q *PermissionQuery) FirstIDX(ctx context.Context) string {
|
||||
id, err := _q.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single Permission entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when more than one Permission entity is found.
|
||||
// Returns a *NotFoundError when no Permission entities are found.
|
||||
func (_q *PermissionQuery) Only(ctx context.Context) (*Permission, error) {
|
||||
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch len(nodes) {
|
||||
case 1:
|
||||
return nodes[0], nil
|
||||
case 0:
|
||||
return nil, &NotFoundError{permission.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{permission.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (_q *PermissionQuery) OnlyX(ctx context.Context) *Permission {
|
||||
node, err := _q.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only Permission ID in the query.
|
||||
// Returns a *NotSingularError when more than one Permission ID is found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (_q *PermissionQuery) OnlyID(ctx context.Context) (id string, err error) {
|
||||
var ids []string
|
||||
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(ids) {
|
||||
case 1:
|
||||
id = ids[0]
|
||||
case 0:
|
||||
err = &NotFoundError{permission.Label}
|
||||
default:
|
||||
err = &NotSingularError{permission.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (_q *PermissionQuery) OnlyIDX(ctx context.Context) string {
|
||||
id, err := _q.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of Permissions.
|
||||
func (_q *PermissionQuery) All(ctx context.Context) ([]*Permission, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*Permission, *PermissionQuery]()
|
||||
return withInterceptors[[]*Permission](ctx, _q, qr, _q.inters)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (_q *PermissionQuery) AllX(ctx context.Context) []*Permission {
|
||||
nodes, err := _q.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of Permission IDs.
|
||||
func (_q *PermissionQuery) IDs(ctx context.Context) (ids []string, err error) {
|
||||
if _q.ctx.Unique == nil && _q.path != nil {
|
||||
_q.Unique(true)
|
||||
}
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
|
||||
if err = _q.Select(permission.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (_q *PermissionQuery) IDsX(ctx context.Context) []string {
|
||||
ids, err := _q.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (_q *PermissionQuery) Count(ctx context.Context) (int, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return withInterceptors[int](ctx, _q, querierCount[*PermissionQuery](), _q.inters)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (_q *PermissionQuery) CountX(ctx context.Context) int {
|
||||
count, err := _q.Count(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// Exist returns true if the query has elements in the graph.
|
||||
func (_q *PermissionQuery) Exist(ctx context.Context) (bool, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
|
||||
switch _, err := _q.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExistX is like Exist, but panics if an error occurs.
|
||||
func (_q *PermissionQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := _q.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the PermissionQuery builder, including all associated steps. It can be
|
||||
// used to prepare common query builders and use them differently after the clone is made.
|
||||
func (_q *PermissionQuery) Clone() *PermissionQuery {
|
||||
if _q == nil {
|
||||
return nil
|
||||
}
|
||||
return &PermissionQuery{
|
||||
config: _q.config,
|
||||
ctx: _q.ctx.Clone(),
|
||||
order: append([]permission.OrderOption{}, _q.order...),
|
||||
inters: append([]Interceptor{}, _q.inters...),
|
||||
predicates: append([]predicate.Permission{}, _q.predicates...),
|
||||
withRolePermissions: _q.withRolePermissions.Clone(),
|
||||
// clone intermediate query.
|
||||
sql: _q.sql.Clone(),
|
||||
path: _q.path,
|
||||
}
|
||||
}
|
||||
|
||||
// WithRolePermissions tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "role_permissions" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *PermissionQuery) WithRolePermissions(opts ...func(*RolePermissionQuery)) *PermissionQuery {
|
||||
query := (&RolePermissionClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withRolePermissions = query
|
||||
return _q
|
||||
}
|
||||
|
||||
// GroupBy is used to group vertices by one or more fields/columns.
|
||||
// It is often used with aggregate functions, like: count, max, mean, min, sum.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// Name string `json:"name,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.Permission.Query().
|
||||
// GroupBy(permission.FieldName).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *PermissionQuery) GroupBy(field string, fields ...string) *PermissionGroupBy {
|
||||
_q.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &PermissionGroupBy{build: _q}
|
||||
grbuild.flds = &_q.ctx.Fields
|
||||
grbuild.label = permission.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.Permission.Query().
|
||||
// Select(permission.FieldName).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *PermissionQuery) Select(fields ...string) *PermissionSelect {
|
||||
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
|
||||
sbuild := &PermissionSelect{PermissionQuery: _q}
|
||||
sbuild.label = permission.Label
|
||||
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a PermissionSelect configured with the given aggregations.
|
||||
func (_q *PermissionQuery) Aggregate(fns ...AggregateFunc) *PermissionSelect {
|
||||
return _q.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (_q *PermissionQuery) prepareQuery(ctx context.Context) error {
|
||||
for _, inter := range _q.inters {
|
||||
if inter == nil {
|
||||
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
|
||||
}
|
||||
if trv, ok := inter.(Traverser); ok {
|
||||
if err := trv.Traverse(ctx, _q); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range _q.ctx.Fields {
|
||||
if !permission.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
}
|
||||
if _q.path != nil {
|
||||
prev, err := _q.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_q.sql = prev
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *PermissionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Permission, error) {
|
||||
var (
|
||||
nodes = []*Permission{}
|
||||
_spec = _q.querySpec()
|
||||
loadedTypes = [1]bool{
|
||||
_q.withRolePermissions != nil,
|
||||
}
|
||||
)
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*Permission).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &Permission{config: _q.config}
|
||||
nodes = append(nodes, node)
|
||||
node.Edges.loadedTypes = loadedTypes
|
||||
return node.assignValues(columns, values)
|
||||
}
|
||||
for i := range hooks {
|
||||
hooks[i](ctx, _spec)
|
||||
}
|
||||
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nodes, nil
|
||||
}
|
||||
if query := _q.withRolePermissions; query != nil {
|
||||
if err := _q.loadRolePermissions(ctx, query, nodes,
|
||||
func(n *Permission) { n.Edges.RolePermissions = []*RolePermission{} },
|
||||
func(n *Permission, e *RolePermission) { n.Edges.RolePermissions = append(n.Edges.RolePermissions, e) }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (_q *PermissionQuery) loadRolePermissions(ctx context.Context, query *RolePermissionQuery, nodes []*Permission, init func(*Permission), assign func(*Permission, *RolePermission)) error {
|
||||
fks := make([]driver.Value, 0, len(nodes))
|
||||
nodeids := make(map[string]*Permission)
|
||||
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.RolePermission(func(s *sql.Selector) {
|
||||
s.Where(sql.InValues(s.C(permission.RolePermissionsColumn), fks...))
|
||||
}))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range neighbors {
|
||||
fk := n.permission_role_permissions
|
||||
if fk == nil {
|
||||
return fmt.Errorf(`foreign-key "permission_role_permissions" is nil for node %v`, n.ID)
|
||||
}
|
||||
node, ok := nodeids[*fk]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected referenced foreign-key "permission_role_permissions" returned %v for node %v`, *fk, n.ID)
|
||||
}
|
||||
assign(node, n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *PermissionQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := _q.querySpec()
|
||||
_spec.Node.Columns = _q.ctx.Fields
|
||||
if len(_q.ctx.Fields) > 0 {
|
||||
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
|
||||
}
|
||||
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
|
||||
}
|
||||
|
||||
func (_q *PermissionQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := sqlgraph.NewQuerySpec(permission.Table, permission.Columns, sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString))
|
||||
_spec.From = _q.sql
|
||||
if unique := _q.ctx.Unique; unique != nil {
|
||||
_spec.Unique = *unique
|
||||
} else if _q.path != nil {
|
||||
_spec.Unique = true
|
||||
}
|
||||
if fields := _q.ctx.Fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, permission.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != permission.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := _q.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit := _q.ctx.Limit; limit != nil {
|
||||
_spec.Limit = *limit
|
||||
}
|
||||
if offset := _q.ctx.Offset; offset != nil {
|
||||
_spec.Offset = *offset
|
||||
}
|
||||
if ps := _q.order; len(ps) > 0 {
|
||||
_spec.Order = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
return _spec
|
||||
}
|
||||
|
||||
func (_q *PermissionQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(_q.driver.Dialect())
|
||||
t1 := builder.Table(permission.Table)
|
||||
columns := _q.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = permission.Columns
|
||||
}
|
||||
selector := builder.Select(t1.Columns(columns...)...).From(t1)
|
||||
if _q.sql != nil {
|
||||
selector = _q.sql
|
||||
selector.Select(selector.Columns(columns...)...)
|
||||
}
|
||||
if _q.ctx.Unique != nil && *_q.ctx.Unique {
|
||||
selector.Distinct()
|
||||
}
|
||||
for _, p := range _q.predicates {
|
||||
p(selector)
|
||||
}
|
||||
for _, p := range _q.order {
|
||||
p(selector)
|
||||
}
|
||||
if offset := _q.ctx.Offset; offset != nil {
|
||||
// limit is mandatory for offset clause. We start
|
||||
// with default value, and override it below if needed.
|
||||
selector.Offset(*offset).Limit(math.MaxInt32)
|
||||
}
|
||||
if limit := _q.ctx.Limit; limit != nil {
|
||||
selector.Limit(*limit)
|
||||
}
|
||||
return selector
|
||||
}
|
||||
|
||||
// PermissionGroupBy is the group-by builder for Permission entities.
|
||||
type PermissionGroupBy struct {
|
||||
selector
|
||||
build *PermissionQuery
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (_g *PermissionGroupBy) Aggregate(fns ...AggregateFunc) *PermissionGroupBy {
|
||||
_g.fns = append(_g.fns, fns...)
|
||||
return _g
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_g *PermissionGroupBy) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
|
||||
if err := _g.build.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*PermissionQuery, *PermissionGroupBy](ctx, _g.build, _g, _g.build.inters, v)
|
||||
}
|
||||
|
||||
func (_g *PermissionGroupBy) sqlScan(ctx context.Context, root *PermissionQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx).Select()
|
||||
aggregation := make([]string, 0, len(_g.fns))
|
||||
for _, fn := range _g.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
|
||||
for _, f := range *_g.flds {
|
||||
columns = append(columns, selector.C(f))
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
selector.GroupBy(selector.Columns(*_g.flds...)...)
|
||||
if err := selector.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
// PermissionSelect is the builder for selecting fields of Permission entities.
|
||||
type PermissionSelect struct {
|
||||
*PermissionQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (_s *PermissionSelect) Aggregate(fns ...AggregateFunc) *PermissionSelect {
|
||||
_s.fns = append(_s.fns, fns...)
|
||||
return _s
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_s *PermissionSelect) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
|
||||
if err := _s.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*PermissionQuery, *PermissionSelect](ctx, _s.PermissionQuery, _s, _s.inters, v)
|
||||
}
|
||||
|
||||
func (_s *PermissionSelect) sqlScan(ctx context.Context, root *PermissionQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx)
|
||||
aggregation := make([]string, 0, len(_s.fns))
|
||||
for _, fn := range _s.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
switch n := len(*_s.selector.flds); {
|
||||
case n == 0 && len(aggregation) > 0:
|
||||
selector.Select(aggregation...)
|
||||
case n != 0 && len(aggregation) > 0:
|
||||
selector.AppendSelect(aggregation...)
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
398
internal/ent/permission_update.go
Normal file
398
internal/ent/permission_update.go
Normal file
@@ -0,0 +1,398 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/permission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/rolepermission"
|
||||
)
|
||||
|
||||
// PermissionUpdate is the builder for updating Permission entities.
|
||||
type PermissionUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *PermissionMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the PermissionUpdate builder.
|
||||
func (_u *PermissionUpdate) Where(ps ...predicate.Permission) *PermissionUpdate {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetName sets the "name" field.
|
||||
func (_u *PermissionUpdate) SetName(v string) *PermissionUpdate {
|
||||
_u.mutation.SetName(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableName sets the "name" field if the given value is not nil.
|
||||
func (_u *PermissionUpdate) SetNillableName(v *string) *PermissionUpdate {
|
||||
if v != nil {
|
||||
_u.SetName(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddRolePermissionIDs adds the "role_permissions" edge to the RolePermission entity by IDs.
|
||||
func (_u *PermissionUpdate) AddRolePermissionIDs(ids ...int) *PermissionUpdate {
|
||||
_u.mutation.AddRolePermissionIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddRolePermissions adds the "role_permissions" edges to the RolePermission entity.
|
||||
func (_u *PermissionUpdate) AddRolePermissions(v ...*RolePermission) *PermissionUpdate {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddRolePermissionIDs(ids...)
|
||||
}
|
||||
|
||||
// Mutation returns the PermissionMutation object of the builder.
|
||||
func (_u *PermissionUpdate) Mutation() *PermissionMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearRolePermissions clears all "role_permissions" edges to the RolePermission entity.
|
||||
func (_u *PermissionUpdate) ClearRolePermissions() *PermissionUpdate {
|
||||
_u.mutation.ClearRolePermissions()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveRolePermissionIDs removes the "role_permissions" edge to RolePermission entities by IDs.
|
||||
func (_u *PermissionUpdate) RemoveRolePermissionIDs(ids ...int) *PermissionUpdate {
|
||||
_u.mutation.RemoveRolePermissionIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveRolePermissions removes "role_permissions" edges to RolePermission entities.
|
||||
func (_u *PermissionUpdate) RemoveRolePermissions(v ...*RolePermission) *PermissionUpdate {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveRolePermissionIDs(ids...)
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (_u *PermissionUpdate) Save(ctx context.Context) (int, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *PermissionUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_u *PermissionUpdate) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *PermissionUpdate) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *PermissionUpdate) check() error {
|
||||
if v, ok := _u.mutation.Name(); ok {
|
||||
if err := permission.NameValidator(v); err != nil {
|
||||
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Permission.name": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *PermissionUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(permission.Table, permission.Columns, sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString))
|
||||
if ps := _u.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := _u.mutation.Name(); ok {
|
||||
_spec.SetField(permission.FieldName, field.TypeString, value)
|
||||
}
|
||||
if _u.mutation.RolePermissionsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: permission.RolePermissionsTable,
|
||||
Columns: []string{permission.RolePermissionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedRolePermissionsIDs(); len(nodes) > 0 && !_u.mutation.RolePermissionsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: permission.RolePermissionsTable,
|
||||
Columns: []string{permission.RolePermissionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(rolepermission.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 := _u.mutation.RolePermissionsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: permission.RolePermissionsTable,
|
||||
Columns: []string{permission.RolePermissionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{permission.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
// PermissionUpdateOne is the builder for updating a single Permission entity.
|
||||
type PermissionUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *PermissionMutation
|
||||
}
|
||||
|
||||
// SetName sets the "name" field.
|
||||
func (_u *PermissionUpdateOne) SetName(v string) *PermissionUpdateOne {
|
||||
_u.mutation.SetName(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableName sets the "name" field if the given value is not nil.
|
||||
func (_u *PermissionUpdateOne) SetNillableName(v *string) *PermissionUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetName(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddRolePermissionIDs adds the "role_permissions" edge to the RolePermission entity by IDs.
|
||||
func (_u *PermissionUpdateOne) AddRolePermissionIDs(ids ...int) *PermissionUpdateOne {
|
||||
_u.mutation.AddRolePermissionIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddRolePermissions adds the "role_permissions" edges to the RolePermission entity.
|
||||
func (_u *PermissionUpdateOne) AddRolePermissions(v ...*RolePermission) *PermissionUpdateOne {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddRolePermissionIDs(ids...)
|
||||
}
|
||||
|
||||
// Mutation returns the PermissionMutation object of the builder.
|
||||
func (_u *PermissionUpdateOne) Mutation() *PermissionMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearRolePermissions clears all "role_permissions" edges to the RolePermission entity.
|
||||
func (_u *PermissionUpdateOne) ClearRolePermissions() *PermissionUpdateOne {
|
||||
_u.mutation.ClearRolePermissions()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveRolePermissionIDs removes the "role_permissions" edge to RolePermission entities by IDs.
|
||||
func (_u *PermissionUpdateOne) RemoveRolePermissionIDs(ids ...int) *PermissionUpdateOne {
|
||||
_u.mutation.RemoveRolePermissionIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveRolePermissions removes "role_permissions" edges to RolePermission entities.
|
||||
func (_u *PermissionUpdateOne) RemoveRolePermissions(v ...*RolePermission) *PermissionUpdateOne {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveRolePermissionIDs(ids...)
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the PermissionUpdate builder.
|
||||
func (_u *PermissionUpdateOne) Where(ps ...predicate.Permission) *PermissionUpdateOne {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Select allows selecting one or more fields (columns) of the returned entity.
|
||||
// The default is selecting all fields defined in the entity schema.
|
||||
func (_u *PermissionUpdateOne) Select(field string, fields ...string) *PermissionUpdateOne {
|
||||
_u.fields = append([]string{field}, fields...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated Permission entity.
|
||||
func (_u *PermissionUpdateOne) Save(ctx context.Context) (*Permission, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *PermissionUpdateOne) SaveX(ctx context.Context) *Permission {
|
||||
node, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (_u *PermissionUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *PermissionUpdateOne) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *PermissionUpdateOne) check() error {
|
||||
if v, ok := _u.mutation.Name(); ok {
|
||||
if err := permission.NameValidator(v); err != nil {
|
||||
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Permission.name": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *PermissionUpdateOne) sqlSave(ctx context.Context) (_node *Permission, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(permission.Table, permission.Columns, sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString))
|
||||
id, ok := _u.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Permission.id" for update`)}
|
||||
}
|
||||
_spec.Node.ID.Value = id
|
||||
if fields := _u.fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, permission.FieldID)
|
||||
for _, f := range fields {
|
||||
if !permission.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != permission.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := _u.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := _u.mutation.Name(); ok {
|
||||
_spec.SetField(permission.FieldName, field.TypeString, value)
|
||||
}
|
||||
if _u.mutation.RolePermissionsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: permission.RolePermissionsTable,
|
||||
Columns: []string{permission.RolePermissionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedRolePermissionsIDs(); len(nodes) > 0 && !_u.mutation.RolePermissionsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: permission.RolePermissionsTable,
|
||||
Columns: []string{permission.RolePermissionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(rolepermission.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 := _u.mutation.RolePermissionsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: permission.RolePermissionsTable,
|
||||
Columns: []string{permission.RolePermissionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
_node = &Permission{config: _u.config}
|
||||
_spec.Assign = _node.assignValues
|
||||
_spec.ScanValues = _node.scanValues
|
||||
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{permission.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
25
internal/ent/predicate/predicate.go
Normal file
25
internal/ent/predicate/predicate.go
Normal file
@@ -0,0 +1,25 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package predicate
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
// AuditLog is the predicate function for auditlog builders.
|
||||
type AuditLog func(*sql.Selector)
|
||||
|
||||
// Permission is the predicate function for permission builders.
|
||||
type Permission func(*sql.Selector)
|
||||
|
||||
// Role is the predicate function for role builders.
|
||||
type Role func(*sql.Selector)
|
||||
|
||||
// RolePermission is the predicate function for rolepermission builders.
|
||||
type RolePermission func(*sql.Selector)
|
||||
|
||||
// User is the predicate function for user builders.
|
||||
type User func(*sql.Selector)
|
||||
|
||||
// UserRole is the predicate function for userrole builders.
|
||||
type UserRole func(*sql.Selector)
|
||||
168
internal/ent/role.go
Normal file
168
internal/ent/role.go
Normal file
@@ -0,0 +1,168 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
)
|
||||
|
||||
// Role is the model entity for the Role schema.
|
||||
type Role struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID string `json:"id,omitempty"`
|
||||
// Name holds the value of the "name" field.
|
||||
Name string `json:"name,omitempty"`
|
||||
// Description holds the value of the "description" field.
|
||||
Description string `json:"description,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 RoleQuery when eager-loading is set.
|
||||
Edges RoleEdges `json:"edges"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// RoleEdges holds the relations/edges for other nodes in the graph.
|
||||
type RoleEdges struct {
|
||||
// RolePermissions holds the value of the role_permissions edge.
|
||||
RolePermissions []*RolePermission `json:"role_permissions,omitempty"`
|
||||
// UserRoles holds the value of the user_roles edge.
|
||||
UserRoles []*UserRole `json:"user_roles,omitempty"`
|
||||
// loadedTypes holds the information for reporting if a
|
||||
// type was loaded (or requested) in eager-loading or not.
|
||||
loadedTypes [2]bool
|
||||
}
|
||||
|
||||
// RolePermissionsOrErr returns the RolePermissions value or an error if the edge
|
||||
// was not loaded in eager-loading.
|
||||
func (e RoleEdges) RolePermissionsOrErr() ([]*RolePermission, error) {
|
||||
if e.loadedTypes[0] {
|
||||
return e.RolePermissions, nil
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "role_permissions"}
|
||||
}
|
||||
|
||||
// UserRolesOrErr returns the UserRoles value or an error if the edge
|
||||
// was not loaded in eager-loading.
|
||||
func (e RoleEdges) UserRolesOrErr() ([]*UserRole, error) {
|
||||
if e.loadedTypes[1] {
|
||||
return e.UserRoles, nil
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "user_roles"}
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*Role) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case role.FieldID, role.FieldName, role.FieldDescription:
|
||||
values[i] = new(sql.NullString)
|
||||
case role.FieldCreatedAt:
|
||||
values[i] = new(sql.NullTime)
|
||||
default:
|
||||
values[i] = new(sql.UnknownType)
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// assignValues assigns the values that were returned from sql.Rows (after scanning)
|
||||
// to the Role fields.
|
||||
func (_m *Role) 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 role.FieldID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ID = value.String
|
||||
}
|
||||
case role.FieldName:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field name", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Name = value.String
|
||||
}
|
||||
case role.FieldDescription:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field description", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Description = value.String
|
||||
}
|
||||
case role.FieldCreatedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field created_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.CreatedAt = value.Time
|
||||
}
|
||||
default:
|
||||
_m.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value returns the ent.Value that was dynamically selected and assigned to the Role.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (_m *Role) Value(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// QueryRolePermissions queries the "role_permissions" edge of the Role entity.
|
||||
func (_m *Role) QueryRolePermissions() *RolePermissionQuery {
|
||||
return NewRoleClient(_m.config).QueryRolePermissions(_m)
|
||||
}
|
||||
|
||||
// QueryUserRoles queries the "user_roles" edge of the Role entity.
|
||||
func (_m *Role) QueryUserRoles() *UserRoleQuery {
|
||||
return NewRoleClient(_m.config).QueryUserRoles(_m)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this Role.
|
||||
// Note that you need to call Role.Unwrap() before calling this method if this Role
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (_m *Role) Update() *RoleUpdateOne {
|
||||
return NewRoleClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the Role entity that was returned from a transaction after it was closed,
|
||||
// so that all future queries will be executed through the driver which created the transaction.
|
||||
func (_m *Role) Unwrap() *Role {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: Role is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *Role) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("Role(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
builder.WriteString("name=")
|
||||
builder.WriteString(_m.Name)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("description=")
|
||||
builder.WriteString(_m.Description)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("created_at=")
|
||||
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// Roles is a parsable slice of Role.
|
||||
type Roles []*Role
|
||||
133
internal/ent/role/role.go
Normal file
133
internal/ent/role/role.go
Normal file
@@ -0,0 +1,133 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package role
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the role type in the database.
|
||||
Label = "role"
|
||||
// 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"
|
||||
// FieldDescription holds the string denoting the description field in the database.
|
||||
FieldDescription = "description"
|
||||
// FieldCreatedAt holds the string denoting the created_at field in the database.
|
||||
FieldCreatedAt = "created_at"
|
||||
// EdgeRolePermissions holds the string denoting the role_permissions edge name in mutations.
|
||||
EdgeRolePermissions = "role_permissions"
|
||||
// EdgeUserRoles holds the string denoting the user_roles edge name in mutations.
|
||||
EdgeUserRoles = "user_roles"
|
||||
// Table holds the table name of the role in the database.
|
||||
Table = "roles"
|
||||
// RolePermissionsTable is the table that holds the role_permissions relation/edge.
|
||||
RolePermissionsTable = "role_permissions"
|
||||
// RolePermissionsInverseTable is the table name for the RolePermission entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "rolepermission" package.
|
||||
RolePermissionsInverseTable = "role_permissions"
|
||||
// RolePermissionsColumn is the table column denoting the role_permissions relation/edge.
|
||||
RolePermissionsColumn = "role_role_permissions"
|
||||
// UserRolesTable is the table that holds the user_roles relation/edge.
|
||||
UserRolesTable = "user_roles"
|
||||
// UserRolesInverseTable is the table name for the UserRole entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "userrole" package.
|
||||
UserRolesInverseTable = "user_roles"
|
||||
// UserRolesColumn is the table column denoting the user_roles relation/edge.
|
||||
UserRolesColumn = "role_user_roles"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for role fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldName,
|
||||
FieldDescription,
|
||||
FieldCreatedAt,
|
||||
}
|
||||
|
||||
// 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 (
|
||||
// NameValidator is a validator for the "name" field. It is called by the builders before save.
|
||||
NameValidator 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 Role 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()
|
||||
}
|
||||
|
||||
// ByDescription orders the results by the description field.
|
||||
func ByDescription(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldDescription, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCreatedAt orders the results by the created_at field.
|
||||
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByRolePermissionsCount orders the results by role_permissions count.
|
||||
func ByRolePermissionsCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborsCount(s, newRolePermissionsStep(), opts...)
|
||||
}
|
||||
}
|
||||
|
||||
// ByRolePermissions orders the results by role_permissions terms.
|
||||
func ByRolePermissions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newRolePermissionsStep(), append([]sql.OrderTerm{term}, terms...)...)
|
||||
}
|
||||
}
|
||||
|
||||
// ByUserRolesCount orders the results by user_roles count.
|
||||
func ByUserRolesCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborsCount(s, newUserRolesStep(), opts...)
|
||||
}
|
||||
}
|
||||
|
||||
// ByUserRoles orders the results by user_roles terms.
|
||||
func ByUserRoles(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newUserRolesStep(), append([]sql.OrderTerm{term}, terms...)...)
|
||||
}
|
||||
}
|
||||
func newRolePermissionsStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(RolePermissionsInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, RolePermissionsTable, RolePermissionsColumn),
|
||||
)
|
||||
}
|
||||
func newUserRolesStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(UserRolesInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, UserRolesTable, UserRolesColumn),
|
||||
)
|
||||
}
|
||||
322
internal/ent/role/where.go
Normal file
322
internal/ent/role/where.go
Normal file
@@ -0,0 +1,322 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package role
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id string) predicate.Role {
|
||||
return predicate.Role(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id string) predicate.Role {
|
||||
return predicate.Role(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id string) predicate.Role {
|
||||
return predicate.Role(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...string) predicate.Role {
|
||||
return predicate.Role(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...string) predicate.Role {
|
||||
return predicate.Role(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id string) predicate.Role {
|
||||
return predicate.Role(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id string) predicate.Role {
|
||||
return predicate.Role(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id string) predicate.Role {
|
||||
return predicate.Role(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id string) predicate.Role {
|
||||
return predicate.Role(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEqualFold applies the EqualFold predicate on the ID field.
|
||||
func IDEqualFold(id string) predicate.Role {
|
||||
return predicate.Role(sql.FieldEqualFold(FieldID, id))
|
||||
}
|
||||
|
||||
// IDContainsFold applies the ContainsFold predicate on the ID field.
|
||||
func IDContainsFold(id string) predicate.Role {
|
||||
return predicate.Role(sql.FieldContainsFold(FieldID, id))
|
||||
}
|
||||
|
||||
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
|
||||
func Name(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldEQ(FieldName, v))
|
||||
}
|
||||
|
||||
// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ.
|
||||
func Description(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldEQ(FieldDescription, v))
|
||||
}
|
||||
|
||||
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
|
||||
func CreatedAt(v time.Time) predicate.Role {
|
||||
return predicate.Role(sql.FieldEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// NameEQ applies the EQ predicate on the "name" field.
|
||||
func NameEQ(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldEQ(FieldName, v))
|
||||
}
|
||||
|
||||
// NameNEQ applies the NEQ predicate on the "name" field.
|
||||
func NameNEQ(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldNEQ(FieldName, v))
|
||||
}
|
||||
|
||||
// NameIn applies the In predicate on the "name" field.
|
||||
func NameIn(vs ...string) predicate.Role {
|
||||
return predicate.Role(sql.FieldIn(FieldName, vs...))
|
||||
}
|
||||
|
||||
// NameNotIn applies the NotIn predicate on the "name" field.
|
||||
func NameNotIn(vs ...string) predicate.Role {
|
||||
return predicate.Role(sql.FieldNotIn(FieldName, vs...))
|
||||
}
|
||||
|
||||
// NameGT applies the GT predicate on the "name" field.
|
||||
func NameGT(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldGT(FieldName, v))
|
||||
}
|
||||
|
||||
// NameGTE applies the GTE predicate on the "name" field.
|
||||
func NameGTE(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldGTE(FieldName, v))
|
||||
}
|
||||
|
||||
// NameLT applies the LT predicate on the "name" field.
|
||||
func NameLT(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldLT(FieldName, v))
|
||||
}
|
||||
|
||||
// NameLTE applies the LTE predicate on the "name" field.
|
||||
func NameLTE(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldLTE(FieldName, v))
|
||||
}
|
||||
|
||||
// NameContains applies the Contains predicate on the "name" field.
|
||||
func NameContains(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldContains(FieldName, v))
|
||||
}
|
||||
|
||||
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
|
||||
func NameHasPrefix(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldHasPrefix(FieldName, v))
|
||||
}
|
||||
|
||||
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
|
||||
func NameHasSuffix(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldHasSuffix(FieldName, v))
|
||||
}
|
||||
|
||||
// NameEqualFold applies the EqualFold predicate on the "name" field.
|
||||
func NameEqualFold(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldEqualFold(FieldName, v))
|
||||
}
|
||||
|
||||
// NameContainsFold applies the ContainsFold predicate on the "name" field.
|
||||
func NameContainsFold(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldContainsFold(FieldName, v))
|
||||
}
|
||||
|
||||
// DescriptionEQ applies the EQ predicate on the "description" field.
|
||||
func DescriptionEQ(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldEQ(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionNEQ applies the NEQ predicate on the "description" field.
|
||||
func DescriptionNEQ(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldNEQ(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionIn applies the In predicate on the "description" field.
|
||||
func DescriptionIn(vs ...string) predicate.Role {
|
||||
return predicate.Role(sql.FieldIn(FieldDescription, vs...))
|
||||
}
|
||||
|
||||
// DescriptionNotIn applies the NotIn predicate on the "description" field.
|
||||
func DescriptionNotIn(vs ...string) predicate.Role {
|
||||
return predicate.Role(sql.FieldNotIn(FieldDescription, vs...))
|
||||
}
|
||||
|
||||
// DescriptionGT applies the GT predicate on the "description" field.
|
||||
func DescriptionGT(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldGT(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionGTE applies the GTE predicate on the "description" field.
|
||||
func DescriptionGTE(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldGTE(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionLT applies the LT predicate on the "description" field.
|
||||
func DescriptionLT(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldLT(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionLTE applies the LTE predicate on the "description" field.
|
||||
func DescriptionLTE(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldLTE(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionContains applies the Contains predicate on the "description" field.
|
||||
func DescriptionContains(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldContains(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field.
|
||||
func DescriptionHasPrefix(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldHasPrefix(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field.
|
||||
func DescriptionHasSuffix(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldHasSuffix(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionIsNil applies the IsNil predicate on the "description" field.
|
||||
func DescriptionIsNil() predicate.Role {
|
||||
return predicate.Role(sql.FieldIsNull(FieldDescription))
|
||||
}
|
||||
|
||||
// DescriptionNotNil applies the NotNil predicate on the "description" field.
|
||||
func DescriptionNotNil() predicate.Role {
|
||||
return predicate.Role(sql.FieldNotNull(FieldDescription))
|
||||
}
|
||||
|
||||
// DescriptionEqualFold applies the EqualFold predicate on the "description" field.
|
||||
func DescriptionEqualFold(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldEqualFold(FieldDescription, v))
|
||||
}
|
||||
|
||||
// DescriptionContainsFold applies the ContainsFold predicate on the "description" field.
|
||||
func DescriptionContainsFold(v string) predicate.Role {
|
||||
return predicate.Role(sql.FieldContainsFold(FieldDescription, v))
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
func CreatedAtEQ(v time.Time) predicate.Role {
|
||||
return predicate.Role(sql.FieldEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
|
||||
func CreatedAtNEQ(v time.Time) predicate.Role {
|
||||
return predicate.Role(sql.FieldNEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtIn applies the In predicate on the "created_at" field.
|
||||
func CreatedAtIn(vs ...time.Time) predicate.Role {
|
||||
return predicate.Role(sql.FieldIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
|
||||
func CreatedAtNotIn(vs ...time.Time) predicate.Role {
|
||||
return predicate.Role(sql.FieldNotIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtGT applies the GT predicate on the "created_at" field.
|
||||
func CreatedAtGT(v time.Time) predicate.Role {
|
||||
return predicate.Role(sql.FieldGT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
|
||||
func CreatedAtGTE(v time.Time) predicate.Role {
|
||||
return predicate.Role(sql.FieldGTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLT applies the LT predicate on the "created_at" field.
|
||||
func CreatedAtLT(v time.Time) predicate.Role {
|
||||
return predicate.Role(sql.FieldLT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
|
||||
func CreatedAtLTE(v time.Time) predicate.Role {
|
||||
return predicate.Role(sql.FieldLTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// HasRolePermissions applies the HasEdge predicate on the "role_permissions" edge.
|
||||
func HasRolePermissions() predicate.Role {
|
||||
return predicate.Role(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, RolePermissionsTable, RolePermissionsColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasRolePermissionsWith applies the HasEdge predicate on the "role_permissions" edge with a given conditions (other predicates).
|
||||
func HasRolePermissionsWith(preds ...predicate.RolePermission) predicate.Role {
|
||||
return predicate.Role(func(s *sql.Selector) {
|
||||
step := newRolePermissionsStep()
|
||||
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
|
||||
for _, p := range preds {
|
||||
p(s)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// HasUserRoles applies the HasEdge predicate on the "user_roles" edge.
|
||||
func HasUserRoles() predicate.Role {
|
||||
return predicate.Role(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, UserRolesTable, UserRolesColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasUserRolesWith applies the HasEdge predicate on the "user_roles" edge with a given conditions (other predicates).
|
||||
func HasUserRolesWith(preds ...predicate.UserRole) predicate.Role {
|
||||
return predicate.Role(func(s *sql.Selector) {
|
||||
step := newUserRolesStep()
|
||||
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.Role) predicate.Role {
|
||||
return predicate.Role(sql.AndPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.Role) predicate.Role {
|
||||
return predicate.Role(sql.OrPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.Role) predicate.Role {
|
||||
return predicate.Role(sql.NotPredicates(p))
|
||||
}
|
||||
313
internal/ent/role_create.go
Normal file
313
internal/ent/role_create.go
Normal file
@@ -0,0 +1,313 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/rolepermission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/userrole"
|
||||
)
|
||||
|
||||
// RoleCreate is the builder for creating a Role entity.
|
||||
type RoleCreate struct {
|
||||
config
|
||||
mutation *RoleMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetName sets the "name" field.
|
||||
func (_c *RoleCreate) SetName(v string) *RoleCreate {
|
||||
_c.mutation.SetName(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetDescription sets the "description" field.
|
||||
func (_c *RoleCreate) SetDescription(v string) *RoleCreate {
|
||||
_c.mutation.SetDescription(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableDescription sets the "description" field if the given value is not nil.
|
||||
func (_c *RoleCreate) SetNillableDescription(v *string) *RoleCreate {
|
||||
if v != nil {
|
||||
_c.SetDescription(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
func (_c *RoleCreate) SetCreatedAt(v time.Time) *RoleCreate {
|
||||
_c.mutation.SetCreatedAt(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
|
||||
func (_c *RoleCreate) SetNillableCreatedAt(v *time.Time) *RoleCreate {
|
||||
if v != nil {
|
||||
_c.SetCreatedAt(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetID sets the "id" field.
|
||||
func (_c *RoleCreate) SetID(v string) *RoleCreate {
|
||||
_c.mutation.SetID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// AddRolePermissionIDs adds the "role_permissions" edge to the RolePermission entity by IDs.
|
||||
func (_c *RoleCreate) AddRolePermissionIDs(ids ...int) *RoleCreate {
|
||||
_c.mutation.AddRolePermissionIDs(ids...)
|
||||
return _c
|
||||
}
|
||||
|
||||
// AddRolePermissions adds the "role_permissions" edges to the RolePermission entity.
|
||||
func (_c *RoleCreate) AddRolePermissions(v ...*RolePermission) *RoleCreate {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _c.AddRolePermissionIDs(ids...)
|
||||
}
|
||||
|
||||
// AddUserRoleIDs adds the "user_roles" edge to the UserRole entity by IDs.
|
||||
func (_c *RoleCreate) AddUserRoleIDs(ids ...int) *RoleCreate {
|
||||
_c.mutation.AddUserRoleIDs(ids...)
|
||||
return _c
|
||||
}
|
||||
|
||||
// AddUserRoles adds the "user_roles" edges to the UserRole entity.
|
||||
func (_c *RoleCreate) AddUserRoles(v ...*UserRole) *RoleCreate {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _c.AddUserRoleIDs(ids...)
|
||||
}
|
||||
|
||||
// Mutation returns the RoleMutation object of the builder.
|
||||
func (_c *RoleCreate) Mutation() *RoleMutation {
|
||||
return _c.mutation
|
||||
}
|
||||
|
||||
// Save creates the Role in the database.
|
||||
func (_c *RoleCreate) Save(ctx context.Context) (*Role, error) {
|
||||
_c.defaults()
|
||||
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (_c *RoleCreate) SaveX(ctx context.Context) *Role {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *RoleCreate) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *RoleCreate) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaults sets the default values of the builder before save.
|
||||
func (_c *RoleCreate) defaults() {
|
||||
if _, ok := _c.mutation.CreatedAt(); !ok {
|
||||
v := role.DefaultCreatedAt()
|
||||
_c.mutation.SetCreatedAt(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_c *RoleCreate) check() error {
|
||||
if _, ok := _c.mutation.Name(); !ok {
|
||||
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Role.name"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.Name(); ok {
|
||||
if err := role.NameValidator(v); err != nil {
|
||||
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Role.name": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.CreatedAt(); !ok {
|
||||
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Role.created_at"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_c *RoleCreate) sqlSave(ctx context.Context) (*Role, error) {
|
||||
if err := _c.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := _c.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if _spec.ID.Value != nil {
|
||||
if id, ok := _spec.ID.Value.(string); ok {
|
||||
_node.ID = id
|
||||
} else {
|
||||
return nil, fmt.Errorf("unexpected Role.ID type: %T", _spec.ID.Value)
|
||||
}
|
||||
}
|
||||
_c.mutation.id = &_node.ID
|
||||
_c.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (_c *RoleCreate) createSpec() (*Role, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &Role{config: _c.config}
|
||||
_spec = sqlgraph.NewCreateSpec(role.Table, sqlgraph.NewFieldSpec(role.FieldID, field.TypeString))
|
||||
)
|
||||
if id, ok := _c.mutation.ID(); ok {
|
||||
_node.ID = id
|
||||
_spec.ID.Value = id
|
||||
}
|
||||
if value, ok := _c.mutation.Name(); ok {
|
||||
_spec.SetField(role.FieldName, field.TypeString, value)
|
||||
_node.Name = value
|
||||
}
|
||||
if value, ok := _c.mutation.Description(); ok {
|
||||
_spec.SetField(role.FieldDescription, field.TypeString, value)
|
||||
_node.Description = value
|
||||
}
|
||||
if value, ok := _c.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(role.FieldCreatedAt, field.TypeTime, value)
|
||||
_node.CreatedAt = value
|
||||
}
|
||||
if nodes := _c.mutation.RolePermissionsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: role.RolePermissionsTable,
|
||||
Columns: []string{role.RolePermissionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
if nodes := _c.mutation.UserRolesIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: role.UserRolesTable,
|
||||
Columns: []string{role.UserRolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// RoleCreateBulk is the builder for creating many Role entities in bulk.
|
||||
type RoleCreateBulk struct {
|
||||
config
|
||||
err error
|
||||
builders []*RoleCreate
|
||||
}
|
||||
|
||||
// Save creates the Role entities in the database.
|
||||
func (_c *RoleCreateBulk) Save(ctx context.Context) ([]*Role, error) {
|
||||
if _c.err != nil {
|
||||
return nil, _c.err
|
||||
}
|
||||
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
|
||||
nodes := make([]*Role, len(_c.builders))
|
||||
mutators := make([]Mutator, len(_c.builders))
|
||||
for i := range _c.builders {
|
||||
func(i int, root context.Context) {
|
||||
builder := _c.builders[i]
|
||||
builder.defaults()
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*RoleMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err := builder.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
builder.mutation = mutation
|
||||
var err error
|
||||
nodes[i], specs[i] = builder.createSpec()
|
||||
if i < len(mutators)-1 {
|
||||
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
|
||||
} else {
|
||||
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
|
||||
// Invoke the actual operation on the latest mutation in the chain.
|
||||
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &nodes[i].ID
|
||||
mutation.done = true
|
||||
return nodes[i], nil
|
||||
})
|
||||
for i := len(builder.hooks) - 1; i >= 0; i-- {
|
||||
mut = builder.hooks[i](mut)
|
||||
}
|
||||
mutators[i] = mut
|
||||
}(i, ctx)
|
||||
}
|
||||
if len(mutators) > 0 {
|
||||
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_c *RoleCreateBulk) SaveX(ctx context.Context) []*Role {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *RoleCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *RoleCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
88
internal/ent/role_delete.go
Normal file
88
internal/ent/role_delete.go
Normal file
@@ -0,0 +1,88 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
)
|
||||
|
||||
// RoleDelete is the builder for deleting a Role entity.
|
||||
type RoleDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *RoleMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the RoleDelete builder.
|
||||
func (_d *RoleDelete) Where(ps ...predicate.Role) *RoleDelete {
|
||||
_d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (_d *RoleDelete) Exec(ctx context.Context) (int, error) {
|
||||
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *RoleDelete) ExecX(ctx context.Context) int {
|
||||
n, err := _d.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (_d *RoleDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(role.Table, sqlgraph.NewFieldSpec(role.FieldID, field.TypeString))
|
||||
if ps := _d.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
|
||||
if err != nil && sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
_d.mutation.done = true
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// RoleDeleteOne is the builder for deleting a single Role entity.
|
||||
type RoleDeleteOne struct {
|
||||
_d *RoleDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the RoleDelete builder.
|
||||
func (_d *RoleDeleteOne) Where(ps ...predicate.Role) *RoleDeleteOne {
|
||||
_d._d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (_d *RoleDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := _d._d.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{role.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *RoleDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := _d.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
682
internal/ent/role_query.go
Normal file
682
internal/ent/role_query.go
Normal file
@@ -0,0 +1,682 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/rolepermission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/userrole"
|
||||
)
|
||||
|
||||
// RoleQuery is the builder for querying Role entities.
|
||||
type RoleQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []role.OrderOption
|
||||
inters []Interceptor
|
||||
predicates []predicate.Role
|
||||
withRolePermissions *RolePermissionQuery
|
||||
withUserRoles *UserRoleQuery
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the RoleQuery builder.
|
||||
func (_q *RoleQuery) Where(ps ...predicate.Role) *RoleQuery {
|
||||
_q.predicates = append(_q.predicates, ps...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
func (_q *RoleQuery) Limit(limit int) *RoleQuery {
|
||||
_q.ctx.Limit = &limit
|
||||
return _q
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
func (_q *RoleQuery) Offset(offset int) *RoleQuery {
|
||||
_q.ctx.Offset = &offset
|
||||
return _q
|
||||
}
|
||||
|
||||
// Unique configures the query builder to filter duplicate records on query.
|
||||
// By default, unique is set to true, and can be disabled using this method.
|
||||
func (_q *RoleQuery) Unique(unique bool) *RoleQuery {
|
||||
_q.ctx.Unique = &unique
|
||||
return _q
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
func (_q *RoleQuery) Order(o ...role.OrderOption) *RoleQuery {
|
||||
_q.order = append(_q.order, o...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// QueryRolePermissions chains the current query on the "role_permissions" edge.
|
||||
func (_q *RoleQuery) QueryRolePermissions() *RolePermissionQuery {
|
||||
query := (&RolePermissionClient{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(role.Table, role.FieldID, selector),
|
||||
sqlgraph.To(rolepermission.Table, rolepermission.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, role.RolePermissionsTable, role.RolePermissionsColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// QueryUserRoles chains the current query on the "user_roles" edge.
|
||||
func (_q *RoleQuery) QueryUserRoles() *UserRoleQuery {
|
||||
query := (&UserRoleClient{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(role.Table, role.FieldID, selector),
|
||||
sqlgraph.To(userrole.Table, userrole.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, role.UserRolesTable, role.UserRolesColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// First returns the first Role entity from the query.
|
||||
// Returns a *NotFoundError when no Role was found.
|
||||
func (_q *RoleQuery) First(ctx context.Context) (*Role, error) {
|
||||
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nil, &NotFoundError{role.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (_q *RoleQuery) FirstX(ctx context.Context) *Role {
|
||||
node, err := _q.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first Role ID from the query.
|
||||
// Returns a *NotFoundError when no Role ID was found.
|
||||
func (_q *RoleQuery) FirstID(ctx context.Context) (id string, err error) {
|
||||
var ids []string
|
||||
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &NotFoundError{role.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (_q *RoleQuery) FirstIDX(ctx context.Context) string {
|
||||
id, err := _q.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single Role entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when more than one Role entity is found.
|
||||
// Returns a *NotFoundError when no Role entities are found.
|
||||
func (_q *RoleQuery) Only(ctx context.Context) (*Role, error) {
|
||||
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch len(nodes) {
|
||||
case 1:
|
||||
return nodes[0], nil
|
||||
case 0:
|
||||
return nil, &NotFoundError{role.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{role.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (_q *RoleQuery) OnlyX(ctx context.Context) *Role {
|
||||
node, err := _q.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only Role ID in the query.
|
||||
// Returns a *NotSingularError when more than one Role ID is found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (_q *RoleQuery) OnlyID(ctx context.Context) (id string, err error) {
|
||||
var ids []string
|
||||
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(ids) {
|
||||
case 1:
|
||||
id = ids[0]
|
||||
case 0:
|
||||
err = &NotFoundError{role.Label}
|
||||
default:
|
||||
err = &NotSingularError{role.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (_q *RoleQuery) OnlyIDX(ctx context.Context) string {
|
||||
id, err := _q.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of Roles.
|
||||
func (_q *RoleQuery) All(ctx context.Context) ([]*Role, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*Role, *RoleQuery]()
|
||||
return withInterceptors[[]*Role](ctx, _q, qr, _q.inters)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (_q *RoleQuery) AllX(ctx context.Context) []*Role {
|
||||
nodes, err := _q.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of Role IDs.
|
||||
func (_q *RoleQuery) IDs(ctx context.Context) (ids []string, err error) {
|
||||
if _q.ctx.Unique == nil && _q.path != nil {
|
||||
_q.Unique(true)
|
||||
}
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
|
||||
if err = _q.Select(role.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (_q *RoleQuery) IDsX(ctx context.Context) []string {
|
||||
ids, err := _q.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (_q *RoleQuery) Count(ctx context.Context) (int, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return withInterceptors[int](ctx, _q, querierCount[*RoleQuery](), _q.inters)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (_q *RoleQuery) CountX(ctx context.Context) int {
|
||||
count, err := _q.Count(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// Exist returns true if the query has elements in the graph.
|
||||
func (_q *RoleQuery) Exist(ctx context.Context) (bool, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
|
||||
switch _, err := _q.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExistX is like Exist, but panics if an error occurs.
|
||||
func (_q *RoleQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := _q.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the RoleQuery builder, including all associated steps. It can be
|
||||
// used to prepare common query builders and use them differently after the clone is made.
|
||||
func (_q *RoleQuery) Clone() *RoleQuery {
|
||||
if _q == nil {
|
||||
return nil
|
||||
}
|
||||
return &RoleQuery{
|
||||
config: _q.config,
|
||||
ctx: _q.ctx.Clone(),
|
||||
order: append([]role.OrderOption{}, _q.order...),
|
||||
inters: append([]Interceptor{}, _q.inters...),
|
||||
predicates: append([]predicate.Role{}, _q.predicates...),
|
||||
withRolePermissions: _q.withRolePermissions.Clone(),
|
||||
withUserRoles: _q.withUserRoles.Clone(),
|
||||
// clone intermediate query.
|
||||
sql: _q.sql.Clone(),
|
||||
path: _q.path,
|
||||
}
|
||||
}
|
||||
|
||||
// WithRolePermissions tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "role_permissions" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *RoleQuery) WithRolePermissions(opts ...func(*RolePermissionQuery)) *RoleQuery {
|
||||
query := (&RolePermissionClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withRolePermissions = query
|
||||
return _q
|
||||
}
|
||||
|
||||
// WithUserRoles tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "user_roles" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *RoleQuery) WithUserRoles(opts ...func(*UserRoleQuery)) *RoleQuery {
|
||||
query := (&UserRoleClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withUserRoles = query
|
||||
return _q
|
||||
}
|
||||
|
||||
// GroupBy is used to group vertices by one or more fields/columns.
|
||||
// It is often used with aggregate functions, like: count, max, mean, min, sum.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// Name string `json:"name,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.Role.Query().
|
||||
// GroupBy(role.FieldName).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *RoleQuery) GroupBy(field string, fields ...string) *RoleGroupBy {
|
||||
_q.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &RoleGroupBy{build: _q}
|
||||
grbuild.flds = &_q.ctx.Fields
|
||||
grbuild.label = role.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.Role.Query().
|
||||
// Select(role.FieldName).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *RoleQuery) Select(fields ...string) *RoleSelect {
|
||||
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
|
||||
sbuild := &RoleSelect{RoleQuery: _q}
|
||||
sbuild.label = role.Label
|
||||
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a RoleSelect configured with the given aggregations.
|
||||
func (_q *RoleQuery) Aggregate(fns ...AggregateFunc) *RoleSelect {
|
||||
return _q.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (_q *RoleQuery) prepareQuery(ctx context.Context) error {
|
||||
for _, inter := range _q.inters {
|
||||
if inter == nil {
|
||||
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
|
||||
}
|
||||
if trv, ok := inter.(Traverser); ok {
|
||||
if err := trv.Traverse(ctx, _q); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range _q.ctx.Fields {
|
||||
if !role.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
}
|
||||
if _q.path != nil {
|
||||
prev, err := _q.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_q.sql = prev
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *RoleQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Role, error) {
|
||||
var (
|
||||
nodes = []*Role{}
|
||||
_spec = _q.querySpec()
|
||||
loadedTypes = [2]bool{
|
||||
_q.withRolePermissions != nil,
|
||||
_q.withUserRoles != nil,
|
||||
}
|
||||
)
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*Role).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &Role{config: _q.config}
|
||||
nodes = append(nodes, node)
|
||||
node.Edges.loadedTypes = loadedTypes
|
||||
return node.assignValues(columns, values)
|
||||
}
|
||||
for i := range hooks {
|
||||
hooks[i](ctx, _spec)
|
||||
}
|
||||
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nodes, nil
|
||||
}
|
||||
if query := _q.withRolePermissions; query != nil {
|
||||
if err := _q.loadRolePermissions(ctx, query, nodes,
|
||||
func(n *Role) { n.Edges.RolePermissions = []*RolePermission{} },
|
||||
func(n *Role, e *RolePermission) { n.Edges.RolePermissions = append(n.Edges.RolePermissions, e) }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if query := _q.withUserRoles; query != nil {
|
||||
if err := _q.loadUserRoles(ctx, query, nodes,
|
||||
func(n *Role) { n.Edges.UserRoles = []*UserRole{} },
|
||||
func(n *Role, e *UserRole) { n.Edges.UserRoles = append(n.Edges.UserRoles, e) }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (_q *RoleQuery) loadRolePermissions(ctx context.Context, query *RolePermissionQuery, nodes []*Role, init func(*Role), assign func(*Role, *RolePermission)) error {
|
||||
fks := make([]driver.Value, 0, len(nodes))
|
||||
nodeids := make(map[string]*Role)
|
||||
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.RolePermission(func(s *sql.Selector) {
|
||||
s.Where(sql.InValues(s.C(role.RolePermissionsColumn), fks...))
|
||||
}))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range neighbors {
|
||||
fk := n.role_role_permissions
|
||||
if fk == nil {
|
||||
return fmt.Errorf(`foreign-key "role_role_permissions" is nil for node %v`, n.ID)
|
||||
}
|
||||
node, ok := nodeids[*fk]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected referenced foreign-key "role_role_permissions" returned %v for node %v`, *fk, n.ID)
|
||||
}
|
||||
assign(node, n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (_q *RoleQuery) loadUserRoles(ctx context.Context, query *UserRoleQuery, nodes []*Role, init func(*Role), assign func(*Role, *UserRole)) error {
|
||||
fks := make([]driver.Value, 0, len(nodes))
|
||||
nodeids := make(map[string]*Role)
|
||||
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.UserRole(func(s *sql.Selector) {
|
||||
s.Where(sql.InValues(s.C(role.UserRolesColumn), fks...))
|
||||
}))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range neighbors {
|
||||
fk := n.role_user_roles
|
||||
if fk == nil {
|
||||
return fmt.Errorf(`foreign-key "role_user_roles" is nil for node %v`, n.ID)
|
||||
}
|
||||
node, ok := nodeids[*fk]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected referenced foreign-key "role_user_roles" returned %v for node %v`, *fk, n.ID)
|
||||
}
|
||||
assign(node, n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *RoleQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := _q.querySpec()
|
||||
_spec.Node.Columns = _q.ctx.Fields
|
||||
if len(_q.ctx.Fields) > 0 {
|
||||
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
|
||||
}
|
||||
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
|
||||
}
|
||||
|
||||
func (_q *RoleQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := sqlgraph.NewQuerySpec(role.Table, role.Columns, sqlgraph.NewFieldSpec(role.FieldID, field.TypeString))
|
||||
_spec.From = _q.sql
|
||||
if unique := _q.ctx.Unique; unique != nil {
|
||||
_spec.Unique = *unique
|
||||
} else if _q.path != nil {
|
||||
_spec.Unique = true
|
||||
}
|
||||
if fields := _q.ctx.Fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, role.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != role.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := _q.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit := _q.ctx.Limit; limit != nil {
|
||||
_spec.Limit = *limit
|
||||
}
|
||||
if offset := _q.ctx.Offset; offset != nil {
|
||||
_spec.Offset = *offset
|
||||
}
|
||||
if ps := _q.order; len(ps) > 0 {
|
||||
_spec.Order = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
return _spec
|
||||
}
|
||||
|
||||
func (_q *RoleQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(_q.driver.Dialect())
|
||||
t1 := builder.Table(role.Table)
|
||||
columns := _q.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = role.Columns
|
||||
}
|
||||
selector := builder.Select(t1.Columns(columns...)...).From(t1)
|
||||
if _q.sql != nil {
|
||||
selector = _q.sql
|
||||
selector.Select(selector.Columns(columns...)...)
|
||||
}
|
||||
if _q.ctx.Unique != nil && *_q.ctx.Unique {
|
||||
selector.Distinct()
|
||||
}
|
||||
for _, p := range _q.predicates {
|
||||
p(selector)
|
||||
}
|
||||
for _, p := range _q.order {
|
||||
p(selector)
|
||||
}
|
||||
if offset := _q.ctx.Offset; offset != nil {
|
||||
// limit is mandatory for offset clause. We start
|
||||
// with default value, and override it below if needed.
|
||||
selector.Offset(*offset).Limit(math.MaxInt32)
|
||||
}
|
||||
if limit := _q.ctx.Limit; limit != nil {
|
||||
selector.Limit(*limit)
|
||||
}
|
||||
return selector
|
||||
}
|
||||
|
||||
// RoleGroupBy is the group-by builder for Role entities.
|
||||
type RoleGroupBy struct {
|
||||
selector
|
||||
build *RoleQuery
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (_g *RoleGroupBy) Aggregate(fns ...AggregateFunc) *RoleGroupBy {
|
||||
_g.fns = append(_g.fns, fns...)
|
||||
return _g
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_g *RoleGroupBy) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
|
||||
if err := _g.build.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*RoleQuery, *RoleGroupBy](ctx, _g.build, _g, _g.build.inters, v)
|
||||
}
|
||||
|
||||
func (_g *RoleGroupBy) sqlScan(ctx context.Context, root *RoleQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx).Select()
|
||||
aggregation := make([]string, 0, len(_g.fns))
|
||||
for _, fn := range _g.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
|
||||
for _, f := range *_g.flds {
|
||||
columns = append(columns, selector.C(f))
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
selector.GroupBy(selector.Columns(*_g.flds...)...)
|
||||
if err := selector.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
// RoleSelect is the builder for selecting fields of Role entities.
|
||||
type RoleSelect struct {
|
||||
*RoleQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (_s *RoleSelect) Aggregate(fns ...AggregateFunc) *RoleSelect {
|
||||
_s.fns = append(_s.fns, fns...)
|
||||
return _s
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_s *RoleSelect) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
|
||||
if err := _s.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*RoleQuery, *RoleSelect](ctx, _s.RoleQuery, _s, _s.inters, v)
|
||||
}
|
||||
|
||||
func (_s *RoleSelect) sqlScan(ctx context.Context, root *RoleQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx)
|
||||
aggregation := make([]string, 0, len(_s.fns))
|
||||
for _, fn := range _s.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
switch n := len(*_s.selector.flds); {
|
||||
case n == 0 && len(aggregation) > 0:
|
||||
selector.Select(aggregation...)
|
||||
case n != 0 && len(aggregation) > 0:
|
||||
selector.AppendSelect(aggregation...)
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
613
internal/ent/role_update.go
Normal file
613
internal/ent/role_update.go
Normal file
@@ -0,0 +1,613 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/rolepermission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/userrole"
|
||||
)
|
||||
|
||||
// RoleUpdate is the builder for updating Role entities.
|
||||
type RoleUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *RoleMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the RoleUpdate builder.
|
||||
func (_u *RoleUpdate) Where(ps ...predicate.Role) *RoleUpdate {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetName sets the "name" field.
|
||||
func (_u *RoleUpdate) SetName(v string) *RoleUpdate {
|
||||
_u.mutation.SetName(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableName sets the "name" field if the given value is not nil.
|
||||
func (_u *RoleUpdate) SetNillableName(v *string) *RoleUpdate {
|
||||
if v != nil {
|
||||
_u.SetName(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetDescription sets the "description" field.
|
||||
func (_u *RoleUpdate) SetDescription(v string) *RoleUpdate {
|
||||
_u.mutation.SetDescription(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableDescription sets the "description" field if the given value is not nil.
|
||||
func (_u *RoleUpdate) SetNillableDescription(v *string) *RoleUpdate {
|
||||
if v != nil {
|
||||
_u.SetDescription(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearDescription clears the value of the "description" field.
|
||||
func (_u *RoleUpdate) ClearDescription() *RoleUpdate {
|
||||
_u.mutation.ClearDescription()
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddRolePermissionIDs adds the "role_permissions" edge to the RolePermission entity by IDs.
|
||||
func (_u *RoleUpdate) AddRolePermissionIDs(ids ...int) *RoleUpdate {
|
||||
_u.mutation.AddRolePermissionIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddRolePermissions adds the "role_permissions" edges to the RolePermission entity.
|
||||
func (_u *RoleUpdate) AddRolePermissions(v ...*RolePermission) *RoleUpdate {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddRolePermissionIDs(ids...)
|
||||
}
|
||||
|
||||
// AddUserRoleIDs adds the "user_roles" edge to the UserRole entity by IDs.
|
||||
func (_u *RoleUpdate) AddUserRoleIDs(ids ...int) *RoleUpdate {
|
||||
_u.mutation.AddUserRoleIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddUserRoles adds the "user_roles" edges to the UserRole entity.
|
||||
func (_u *RoleUpdate) AddUserRoles(v ...*UserRole) *RoleUpdate {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddUserRoleIDs(ids...)
|
||||
}
|
||||
|
||||
// Mutation returns the RoleMutation object of the builder.
|
||||
func (_u *RoleUpdate) Mutation() *RoleMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearRolePermissions clears all "role_permissions" edges to the RolePermission entity.
|
||||
func (_u *RoleUpdate) ClearRolePermissions() *RoleUpdate {
|
||||
_u.mutation.ClearRolePermissions()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveRolePermissionIDs removes the "role_permissions" edge to RolePermission entities by IDs.
|
||||
func (_u *RoleUpdate) RemoveRolePermissionIDs(ids ...int) *RoleUpdate {
|
||||
_u.mutation.RemoveRolePermissionIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveRolePermissions removes "role_permissions" edges to RolePermission entities.
|
||||
func (_u *RoleUpdate) RemoveRolePermissions(v ...*RolePermission) *RoleUpdate {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveRolePermissionIDs(ids...)
|
||||
}
|
||||
|
||||
// ClearUserRoles clears all "user_roles" edges to the UserRole entity.
|
||||
func (_u *RoleUpdate) ClearUserRoles() *RoleUpdate {
|
||||
_u.mutation.ClearUserRoles()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveUserRoleIDs removes the "user_roles" edge to UserRole entities by IDs.
|
||||
func (_u *RoleUpdate) RemoveUserRoleIDs(ids ...int) *RoleUpdate {
|
||||
_u.mutation.RemoveUserRoleIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveUserRoles removes "user_roles" edges to UserRole entities.
|
||||
func (_u *RoleUpdate) RemoveUserRoles(v ...*UserRole) *RoleUpdate {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveUserRoleIDs(ids...)
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (_u *RoleUpdate) Save(ctx context.Context) (int, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *RoleUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_u *RoleUpdate) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *RoleUpdate) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *RoleUpdate) check() error {
|
||||
if v, ok := _u.mutation.Name(); ok {
|
||||
if err := role.NameValidator(v); err != nil {
|
||||
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Role.name": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *RoleUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(role.Table, role.Columns, sqlgraph.NewFieldSpec(role.FieldID, field.TypeString))
|
||||
if ps := _u.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := _u.mutation.Name(); ok {
|
||||
_spec.SetField(role.FieldName, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Description(); ok {
|
||||
_spec.SetField(role.FieldDescription, field.TypeString, value)
|
||||
}
|
||||
if _u.mutation.DescriptionCleared() {
|
||||
_spec.ClearField(role.FieldDescription, field.TypeString)
|
||||
}
|
||||
if _u.mutation.RolePermissionsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: role.RolePermissionsTable,
|
||||
Columns: []string{role.RolePermissionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedRolePermissionsIDs(); len(nodes) > 0 && !_u.mutation.RolePermissionsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: role.RolePermissionsTable,
|
||||
Columns: []string{role.RolePermissionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(rolepermission.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 := _u.mutation.RolePermissionsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: role.RolePermissionsTable,
|
||||
Columns: []string{role.RolePermissionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.UserRolesCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: role.UserRolesTable,
|
||||
Columns: []string{role.UserRolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedUserRolesIDs(); len(nodes) > 0 && !_u.mutation.UserRolesCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: role.UserRolesTable,
|
||||
Columns: []string{role.UserRolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(userrole.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 := _u.mutation.UserRolesIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: role.UserRolesTable,
|
||||
Columns: []string{role.UserRolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{role.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
// RoleUpdateOne is the builder for updating a single Role entity.
|
||||
type RoleUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *RoleMutation
|
||||
}
|
||||
|
||||
// SetName sets the "name" field.
|
||||
func (_u *RoleUpdateOne) SetName(v string) *RoleUpdateOne {
|
||||
_u.mutation.SetName(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableName sets the "name" field if the given value is not nil.
|
||||
func (_u *RoleUpdateOne) SetNillableName(v *string) *RoleUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetName(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetDescription sets the "description" field.
|
||||
func (_u *RoleUpdateOne) SetDescription(v string) *RoleUpdateOne {
|
||||
_u.mutation.SetDescription(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableDescription sets the "description" field if the given value is not nil.
|
||||
func (_u *RoleUpdateOne) SetNillableDescription(v *string) *RoleUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetDescription(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearDescription clears the value of the "description" field.
|
||||
func (_u *RoleUpdateOne) ClearDescription() *RoleUpdateOne {
|
||||
_u.mutation.ClearDescription()
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddRolePermissionIDs adds the "role_permissions" edge to the RolePermission entity by IDs.
|
||||
func (_u *RoleUpdateOne) AddRolePermissionIDs(ids ...int) *RoleUpdateOne {
|
||||
_u.mutation.AddRolePermissionIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddRolePermissions adds the "role_permissions" edges to the RolePermission entity.
|
||||
func (_u *RoleUpdateOne) AddRolePermissions(v ...*RolePermission) *RoleUpdateOne {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddRolePermissionIDs(ids...)
|
||||
}
|
||||
|
||||
// AddUserRoleIDs adds the "user_roles" edge to the UserRole entity by IDs.
|
||||
func (_u *RoleUpdateOne) AddUserRoleIDs(ids ...int) *RoleUpdateOne {
|
||||
_u.mutation.AddUserRoleIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddUserRoles adds the "user_roles" edges to the UserRole entity.
|
||||
func (_u *RoleUpdateOne) AddUserRoles(v ...*UserRole) *RoleUpdateOne {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddUserRoleIDs(ids...)
|
||||
}
|
||||
|
||||
// Mutation returns the RoleMutation object of the builder.
|
||||
func (_u *RoleUpdateOne) Mutation() *RoleMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearRolePermissions clears all "role_permissions" edges to the RolePermission entity.
|
||||
func (_u *RoleUpdateOne) ClearRolePermissions() *RoleUpdateOne {
|
||||
_u.mutation.ClearRolePermissions()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveRolePermissionIDs removes the "role_permissions" edge to RolePermission entities by IDs.
|
||||
func (_u *RoleUpdateOne) RemoveRolePermissionIDs(ids ...int) *RoleUpdateOne {
|
||||
_u.mutation.RemoveRolePermissionIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveRolePermissions removes "role_permissions" edges to RolePermission entities.
|
||||
func (_u *RoleUpdateOne) RemoveRolePermissions(v ...*RolePermission) *RoleUpdateOne {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveRolePermissionIDs(ids...)
|
||||
}
|
||||
|
||||
// ClearUserRoles clears all "user_roles" edges to the UserRole entity.
|
||||
func (_u *RoleUpdateOne) ClearUserRoles() *RoleUpdateOne {
|
||||
_u.mutation.ClearUserRoles()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveUserRoleIDs removes the "user_roles" edge to UserRole entities by IDs.
|
||||
func (_u *RoleUpdateOne) RemoveUserRoleIDs(ids ...int) *RoleUpdateOne {
|
||||
_u.mutation.RemoveUserRoleIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveUserRoles removes "user_roles" edges to UserRole entities.
|
||||
func (_u *RoleUpdateOne) RemoveUserRoles(v ...*UserRole) *RoleUpdateOne {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveUserRoleIDs(ids...)
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the RoleUpdate builder.
|
||||
func (_u *RoleUpdateOne) Where(ps ...predicate.Role) *RoleUpdateOne {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Select allows selecting one or more fields (columns) of the returned entity.
|
||||
// The default is selecting all fields defined in the entity schema.
|
||||
func (_u *RoleUpdateOne) Select(field string, fields ...string) *RoleUpdateOne {
|
||||
_u.fields = append([]string{field}, fields...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated Role entity.
|
||||
func (_u *RoleUpdateOne) Save(ctx context.Context) (*Role, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *RoleUpdateOne) SaveX(ctx context.Context) *Role {
|
||||
node, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (_u *RoleUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *RoleUpdateOne) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *RoleUpdateOne) check() error {
|
||||
if v, ok := _u.mutation.Name(); ok {
|
||||
if err := role.NameValidator(v); err != nil {
|
||||
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Role.name": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *RoleUpdateOne) sqlSave(ctx context.Context) (_node *Role, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(role.Table, role.Columns, sqlgraph.NewFieldSpec(role.FieldID, field.TypeString))
|
||||
id, ok := _u.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Role.id" for update`)}
|
||||
}
|
||||
_spec.Node.ID.Value = id
|
||||
if fields := _u.fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, role.FieldID)
|
||||
for _, f := range fields {
|
||||
if !role.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != role.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := _u.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := _u.mutation.Name(); ok {
|
||||
_spec.SetField(role.FieldName, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Description(); ok {
|
||||
_spec.SetField(role.FieldDescription, field.TypeString, value)
|
||||
}
|
||||
if _u.mutation.DescriptionCleared() {
|
||||
_spec.ClearField(role.FieldDescription, field.TypeString)
|
||||
}
|
||||
if _u.mutation.RolePermissionsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: role.RolePermissionsTable,
|
||||
Columns: []string{role.RolePermissionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedRolePermissionsIDs(); len(nodes) > 0 && !_u.mutation.RolePermissionsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: role.RolePermissionsTable,
|
||||
Columns: []string{role.RolePermissionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(rolepermission.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 := _u.mutation.RolePermissionsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: role.RolePermissionsTable,
|
||||
Columns: []string{role.RolePermissionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.UserRolesCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: role.UserRolesTable,
|
||||
Columns: []string{role.UserRolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedUserRolesIDs(); len(nodes) > 0 && !_u.mutation.UserRolesCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: role.UserRolesTable,
|
||||
Columns: []string{role.UserRolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(userrole.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 := _u.mutation.UserRolesIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: role.UserRolesTable,
|
||||
Columns: []string{role.UserRolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
_node = &Role{config: _u.config}
|
||||
_spec.Assign = _node.assignValues
|
||||
_spec.ScanValues = _node.scanValues
|
||||
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{role.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
182
internal/ent/rolepermission.go
Normal file
182
internal/ent/rolepermission.go
Normal file
@@ -0,0 +1,182 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/permission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/rolepermission"
|
||||
)
|
||||
|
||||
// RolePermission is the model entity for the RolePermission schema.
|
||||
type RolePermission struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID int `json:"id,omitempty"`
|
||||
// RoleID holds the value of the "role_id" field.
|
||||
RoleID string `json:"role_id,omitempty"`
|
||||
// PermissionID holds the value of the "permission_id" field.
|
||||
PermissionID string `json:"permission_id,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
// The values are being populated by the RolePermissionQuery when eager-loading is set.
|
||||
Edges RolePermissionEdges `json:"edges"`
|
||||
permission_role_permissions *string
|
||||
role_role_permissions *string
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// RolePermissionEdges holds the relations/edges for other nodes in the graph.
|
||||
type RolePermissionEdges struct {
|
||||
// Role holds the value of the role edge.
|
||||
Role *Role `json:"role,omitempty"`
|
||||
// Permission holds the value of the permission edge.
|
||||
Permission *Permission `json:"permission,omitempty"`
|
||||
// loadedTypes holds the information for reporting if a
|
||||
// type was loaded (or requested) in eager-loading or not.
|
||||
loadedTypes [2]bool
|
||||
}
|
||||
|
||||
// RoleOrErr returns the Role value or an error if the edge
|
||||
// was not loaded in eager-loading, or loaded but was not found.
|
||||
func (e RolePermissionEdges) RoleOrErr() (*Role, error) {
|
||||
if e.Role != nil {
|
||||
return e.Role, nil
|
||||
} else if e.loadedTypes[0] {
|
||||
return nil, &NotFoundError{label: role.Label}
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "role"}
|
||||
}
|
||||
|
||||
// PermissionOrErr returns the Permission value or an error if the edge
|
||||
// was not loaded in eager-loading, or loaded but was not found.
|
||||
func (e RolePermissionEdges) PermissionOrErr() (*Permission, error) {
|
||||
if e.Permission != nil {
|
||||
return e.Permission, nil
|
||||
} else if e.loadedTypes[1] {
|
||||
return nil, &NotFoundError{label: permission.Label}
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "permission"}
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*RolePermission) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case rolepermission.FieldID:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case rolepermission.FieldRoleID, rolepermission.FieldPermissionID:
|
||||
values[i] = new(sql.NullString)
|
||||
case rolepermission.ForeignKeys[0]: // permission_role_permissions
|
||||
values[i] = new(sql.NullString)
|
||||
case rolepermission.ForeignKeys[1]: // role_role_permissions
|
||||
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 RolePermission fields.
|
||||
func (_m *RolePermission) 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 rolepermission.FieldID:
|
||||
value, ok := values[i].(*sql.NullInt64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", value)
|
||||
}
|
||||
_m.ID = int(value.Int64)
|
||||
case rolepermission.FieldRoleID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field role_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.RoleID = value.String
|
||||
}
|
||||
case rolepermission.FieldPermissionID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field permission_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.PermissionID = value.String
|
||||
}
|
||||
case rolepermission.ForeignKeys[0]:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field permission_role_permissions", values[i])
|
||||
} else if value.Valid {
|
||||
_m.permission_role_permissions = new(string)
|
||||
*_m.permission_role_permissions = value.String
|
||||
}
|
||||
case rolepermission.ForeignKeys[1]:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field role_role_permissions", values[i])
|
||||
} else if value.Valid {
|
||||
_m.role_role_permissions = new(string)
|
||||
*_m.role_role_permissions = value.String
|
||||
}
|
||||
default:
|
||||
_m.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value returns the ent.Value that was dynamically selected and assigned to the RolePermission.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (_m *RolePermission) Value(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// QueryRole queries the "role" edge of the RolePermission entity.
|
||||
func (_m *RolePermission) QueryRole() *RoleQuery {
|
||||
return NewRolePermissionClient(_m.config).QueryRole(_m)
|
||||
}
|
||||
|
||||
// QueryPermission queries the "permission" edge of the RolePermission entity.
|
||||
func (_m *RolePermission) QueryPermission() *PermissionQuery {
|
||||
return NewRolePermissionClient(_m.config).QueryPermission(_m)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this RolePermission.
|
||||
// Note that you need to call RolePermission.Unwrap() before calling this method if this RolePermission
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (_m *RolePermission) Update() *RolePermissionUpdateOne {
|
||||
return NewRolePermissionClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the RolePermission entity that was returned from a transaction after it was closed,
|
||||
// so that all future queries will be executed through the driver which created the transaction.
|
||||
func (_m *RolePermission) Unwrap() *RolePermission {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: RolePermission is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *RolePermission) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("RolePermission(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
builder.WriteString("role_id=")
|
||||
builder.WriteString(_m.RoleID)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("permission_id=")
|
||||
builder.WriteString(_m.PermissionID)
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// RolePermissions is a parsable slice of RolePermission.
|
||||
type RolePermissions []*RolePermission
|
||||
114
internal/ent/rolepermission/rolepermission.go
Normal file
114
internal/ent/rolepermission/rolepermission.go
Normal file
@@ -0,0 +1,114 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package rolepermission
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the rolepermission type in the database.
|
||||
Label = "role_permission"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldRoleID holds the string denoting the role_id field in the database.
|
||||
FieldRoleID = "role_id"
|
||||
// FieldPermissionID holds the string denoting the permission_id field in the database.
|
||||
FieldPermissionID = "permission_id"
|
||||
// EdgeRole holds the string denoting the role edge name in mutations.
|
||||
EdgeRole = "role"
|
||||
// EdgePermission holds the string denoting the permission edge name in mutations.
|
||||
EdgePermission = "permission"
|
||||
// Table holds the table name of the rolepermission in the database.
|
||||
Table = "role_permissions"
|
||||
// RoleTable is the table that holds the role relation/edge.
|
||||
RoleTable = "role_permissions"
|
||||
// RoleInverseTable is the table name for the Role entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "role" package.
|
||||
RoleInverseTable = "roles"
|
||||
// RoleColumn is the table column denoting the role relation/edge.
|
||||
RoleColumn = "role_id"
|
||||
// PermissionTable is the table that holds the permission relation/edge.
|
||||
PermissionTable = "role_permissions"
|
||||
// PermissionInverseTable is the table name for the Permission entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "permission" package.
|
||||
PermissionInverseTable = "permissions"
|
||||
// PermissionColumn is the table column denoting the permission relation/edge.
|
||||
PermissionColumn = "permission_id"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for rolepermission fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldRoleID,
|
||||
FieldPermissionID,
|
||||
}
|
||||
|
||||
// ForeignKeys holds the SQL foreign-keys that are owned by the "role_permissions"
|
||||
// table and are not defined as standalone fields in the schema.
|
||||
var ForeignKeys = []string{
|
||||
"permission_role_permissions",
|
||||
"role_role_permissions",
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// OrderOption defines the ordering options for the RolePermission 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()
|
||||
}
|
||||
|
||||
// ByRoleID orders the results by the role_id field.
|
||||
func ByRoleID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldRoleID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByPermissionID orders the results by the permission_id field.
|
||||
func ByPermissionID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldPermissionID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByRoleField orders the results by role field.
|
||||
func ByRoleField(field string, opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newRoleStep(), sql.OrderByField(field, opts...))
|
||||
}
|
||||
}
|
||||
|
||||
// ByPermissionField orders the results by permission field.
|
||||
func ByPermissionField(field string, opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newPermissionStep(), sql.OrderByField(field, opts...))
|
||||
}
|
||||
}
|
||||
func newRoleStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(RoleInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, false, RoleTable, RoleColumn),
|
||||
)
|
||||
}
|
||||
func newPermissionStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(PermissionInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, false, PermissionTable, PermissionColumn),
|
||||
)
|
||||
}
|
||||
255
internal/ent/rolepermission/where.go
Normal file
255
internal/ent/rolepermission/where.go
Normal file
@@ -0,0 +1,255 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package rolepermission
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id int) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id int) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id int) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...int) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...int) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id int) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id int) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id int) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id int) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// RoleID applies equality check predicate on the "role_id" field. It's identical to RoleIDEQ.
|
||||
func RoleID(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldEQ(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// PermissionID applies equality check predicate on the "permission_id" field. It's identical to PermissionIDEQ.
|
||||
func PermissionID(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldEQ(FieldPermissionID, v))
|
||||
}
|
||||
|
||||
// RoleIDEQ applies the EQ predicate on the "role_id" field.
|
||||
func RoleIDEQ(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldEQ(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDNEQ applies the NEQ predicate on the "role_id" field.
|
||||
func RoleIDNEQ(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldNEQ(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDIn applies the In predicate on the "role_id" field.
|
||||
func RoleIDIn(vs ...string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldIn(FieldRoleID, vs...))
|
||||
}
|
||||
|
||||
// RoleIDNotIn applies the NotIn predicate on the "role_id" field.
|
||||
func RoleIDNotIn(vs ...string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldNotIn(FieldRoleID, vs...))
|
||||
}
|
||||
|
||||
// RoleIDGT applies the GT predicate on the "role_id" field.
|
||||
func RoleIDGT(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldGT(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDGTE applies the GTE predicate on the "role_id" field.
|
||||
func RoleIDGTE(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldGTE(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDLT applies the LT predicate on the "role_id" field.
|
||||
func RoleIDLT(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldLT(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDLTE applies the LTE predicate on the "role_id" field.
|
||||
func RoleIDLTE(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldLTE(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDContains applies the Contains predicate on the "role_id" field.
|
||||
func RoleIDContains(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldContains(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDHasPrefix applies the HasPrefix predicate on the "role_id" field.
|
||||
func RoleIDHasPrefix(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldHasPrefix(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDHasSuffix applies the HasSuffix predicate on the "role_id" field.
|
||||
func RoleIDHasSuffix(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldHasSuffix(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDEqualFold applies the EqualFold predicate on the "role_id" field.
|
||||
func RoleIDEqualFold(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldEqualFold(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDContainsFold applies the ContainsFold predicate on the "role_id" field.
|
||||
func RoleIDContainsFold(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldContainsFold(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// PermissionIDEQ applies the EQ predicate on the "permission_id" field.
|
||||
func PermissionIDEQ(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldEQ(FieldPermissionID, v))
|
||||
}
|
||||
|
||||
// PermissionIDNEQ applies the NEQ predicate on the "permission_id" field.
|
||||
func PermissionIDNEQ(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldNEQ(FieldPermissionID, v))
|
||||
}
|
||||
|
||||
// PermissionIDIn applies the In predicate on the "permission_id" field.
|
||||
func PermissionIDIn(vs ...string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldIn(FieldPermissionID, vs...))
|
||||
}
|
||||
|
||||
// PermissionIDNotIn applies the NotIn predicate on the "permission_id" field.
|
||||
func PermissionIDNotIn(vs ...string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldNotIn(FieldPermissionID, vs...))
|
||||
}
|
||||
|
||||
// PermissionIDGT applies the GT predicate on the "permission_id" field.
|
||||
func PermissionIDGT(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldGT(FieldPermissionID, v))
|
||||
}
|
||||
|
||||
// PermissionIDGTE applies the GTE predicate on the "permission_id" field.
|
||||
func PermissionIDGTE(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldGTE(FieldPermissionID, v))
|
||||
}
|
||||
|
||||
// PermissionIDLT applies the LT predicate on the "permission_id" field.
|
||||
func PermissionIDLT(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldLT(FieldPermissionID, v))
|
||||
}
|
||||
|
||||
// PermissionIDLTE applies the LTE predicate on the "permission_id" field.
|
||||
func PermissionIDLTE(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldLTE(FieldPermissionID, v))
|
||||
}
|
||||
|
||||
// PermissionIDContains applies the Contains predicate on the "permission_id" field.
|
||||
func PermissionIDContains(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldContains(FieldPermissionID, v))
|
||||
}
|
||||
|
||||
// PermissionIDHasPrefix applies the HasPrefix predicate on the "permission_id" field.
|
||||
func PermissionIDHasPrefix(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldHasPrefix(FieldPermissionID, v))
|
||||
}
|
||||
|
||||
// PermissionIDHasSuffix applies the HasSuffix predicate on the "permission_id" field.
|
||||
func PermissionIDHasSuffix(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldHasSuffix(FieldPermissionID, v))
|
||||
}
|
||||
|
||||
// PermissionIDEqualFold applies the EqualFold predicate on the "permission_id" field.
|
||||
func PermissionIDEqualFold(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldEqualFold(FieldPermissionID, v))
|
||||
}
|
||||
|
||||
// PermissionIDContainsFold applies the ContainsFold predicate on the "permission_id" field.
|
||||
func PermissionIDContainsFold(v string) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.FieldContainsFold(FieldPermissionID, v))
|
||||
}
|
||||
|
||||
// HasRole applies the HasEdge predicate on the "role" edge.
|
||||
func HasRole() predicate.RolePermission {
|
||||
return predicate.RolePermission(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, false, RoleTable, RoleColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasRoleWith applies the HasEdge predicate on the "role" edge with a given conditions (other predicates).
|
||||
func HasRoleWith(preds ...predicate.Role) predicate.RolePermission {
|
||||
return predicate.RolePermission(func(s *sql.Selector) {
|
||||
step := newRoleStep()
|
||||
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
|
||||
for _, p := range preds {
|
||||
p(s)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// HasPermission applies the HasEdge predicate on the "permission" edge.
|
||||
func HasPermission() predicate.RolePermission {
|
||||
return predicate.RolePermission(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, false, PermissionTable, PermissionColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasPermissionWith applies the HasEdge predicate on the "permission" edge with a given conditions (other predicates).
|
||||
func HasPermissionWith(preds ...predicate.Permission) predicate.RolePermission {
|
||||
return predicate.RolePermission(func(s *sql.Selector) {
|
||||
step := newPermissionStep()
|
||||
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.RolePermission) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.AndPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.RolePermission) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.OrPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.RolePermission) predicate.RolePermission {
|
||||
return predicate.RolePermission(sql.NotPredicates(p))
|
||||
}
|
||||
240
internal/ent/rolepermission_create.go
Normal file
240
internal/ent/rolepermission_create.go
Normal file
@@ -0,0 +1,240 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/permission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/rolepermission"
|
||||
)
|
||||
|
||||
// RolePermissionCreate is the builder for creating a RolePermission entity.
|
||||
type RolePermissionCreate struct {
|
||||
config
|
||||
mutation *RolePermissionMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetRoleID sets the "role_id" field.
|
||||
func (_c *RolePermissionCreate) SetRoleID(v string) *RolePermissionCreate {
|
||||
_c.mutation.SetRoleID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetPermissionID sets the "permission_id" field.
|
||||
func (_c *RolePermissionCreate) SetPermissionID(v string) *RolePermissionCreate {
|
||||
_c.mutation.SetPermissionID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetRole sets the "role" edge to the Role entity.
|
||||
func (_c *RolePermissionCreate) SetRole(v *Role) *RolePermissionCreate {
|
||||
return _c.SetRoleID(v.ID)
|
||||
}
|
||||
|
||||
// SetPermission sets the "permission" edge to the Permission entity.
|
||||
func (_c *RolePermissionCreate) SetPermission(v *Permission) *RolePermissionCreate {
|
||||
return _c.SetPermissionID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the RolePermissionMutation object of the builder.
|
||||
func (_c *RolePermissionCreate) Mutation() *RolePermissionMutation {
|
||||
return _c.mutation
|
||||
}
|
||||
|
||||
// Save creates the RolePermission in the database.
|
||||
func (_c *RolePermissionCreate) Save(ctx context.Context) (*RolePermission, error) {
|
||||
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (_c *RolePermissionCreate) SaveX(ctx context.Context) *RolePermission {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *RolePermissionCreate) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *RolePermissionCreate) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_c *RolePermissionCreate) check() error {
|
||||
if _, ok := _c.mutation.RoleID(); !ok {
|
||||
return &ValidationError{Name: "role_id", err: errors.New(`ent: missing required field "RolePermission.role_id"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.PermissionID(); !ok {
|
||||
return &ValidationError{Name: "permission_id", err: errors.New(`ent: missing required field "RolePermission.permission_id"`)}
|
||||
}
|
||||
if len(_c.mutation.RoleIDs()) == 0 {
|
||||
return &ValidationError{Name: "role", err: errors.New(`ent: missing required edge "RolePermission.role"`)}
|
||||
}
|
||||
if len(_c.mutation.PermissionIDs()) == 0 {
|
||||
return &ValidationError{Name: "permission", err: errors.New(`ent: missing required edge "RolePermission.permission"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_c *RolePermissionCreate) sqlSave(ctx context.Context) (*RolePermission, error) {
|
||||
if err := _c.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := _c.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
id := _spec.ID.Value.(int64)
|
||||
_node.ID = int(id)
|
||||
_c.mutation.id = &_node.ID
|
||||
_c.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (_c *RolePermissionCreate) createSpec() (*RolePermission, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &RolePermission{config: _c.config}
|
||||
_spec = sqlgraph.NewCreateSpec(rolepermission.Table, sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt))
|
||||
)
|
||||
if nodes := _c.mutation.RoleIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: rolepermission.RoleTable,
|
||||
Columns: []string{rolepermission.RoleColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_node.RoleID = nodes[0]
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
if nodes := _c.mutation.PermissionIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: rolepermission.PermissionTable,
|
||||
Columns: []string{rolepermission.PermissionColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_node.PermissionID = nodes[0]
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// RolePermissionCreateBulk is the builder for creating many RolePermission entities in bulk.
|
||||
type RolePermissionCreateBulk struct {
|
||||
config
|
||||
err error
|
||||
builders []*RolePermissionCreate
|
||||
}
|
||||
|
||||
// Save creates the RolePermission entities in the database.
|
||||
func (_c *RolePermissionCreateBulk) Save(ctx context.Context) ([]*RolePermission, error) {
|
||||
if _c.err != nil {
|
||||
return nil, _c.err
|
||||
}
|
||||
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
|
||||
nodes := make([]*RolePermission, len(_c.builders))
|
||||
mutators := make([]Mutator, len(_c.builders))
|
||||
for i := range _c.builders {
|
||||
func(i int, root context.Context) {
|
||||
builder := _c.builders[i]
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*RolePermissionMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err := builder.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
builder.mutation = mutation
|
||||
var err error
|
||||
nodes[i], specs[i] = builder.createSpec()
|
||||
if i < len(mutators)-1 {
|
||||
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
|
||||
} else {
|
||||
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
|
||||
// Invoke the actual operation on the latest mutation in the chain.
|
||||
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &nodes[i].ID
|
||||
if specs[i].ID.Value != nil {
|
||||
id := specs[i].ID.Value.(int64)
|
||||
nodes[i].ID = int(id)
|
||||
}
|
||||
mutation.done = true
|
||||
return nodes[i], nil
|
||||
})
|
||||
for i := len(builder.hooks) - 1; i >= 0; i-- {
|
||||
mut = builder.hooks[i](mut)
|
||||
}
|
||||
mutators[i] = mut
|
||||
}(i, ctx)
|
||||
}
|
||||
if len(mutators) > 0 {
|
||||
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_c *RolePermissionCreateBulk) SaveX(ctx context.Context) []*RolePermission {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *RolePermissionCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *RolePermissionCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
88
internal/ent/rolepermission_delete.go
Normal file
88
internal/ent/rolepermission_delete.go
Normal file
@@ -0,0 +1,88 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/rolepermission"
|
||||
)
|
||||
|
||||
// RolePermissionDelete is the builder for deleting a RolePermission entity.
|
||||
type RolePermissionDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *RolePermissionMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the RolePermissionDelete builder.
|
||||
func (_d *RolePermissionDelete) Where(ps ...predicate.RolePermission) *RolePermissionDelete {
|
||||
_d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (_d *RolePermissionDelete) Exec(ctx context.Context) (int, error) {
|
||||
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *RolePermissionDelete) ExecX(ctx context.Context) int {
|
||||
n, err := _d.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (_d *RolePermissionDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(rolepermission.Table, sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt))
|
||||
if ps := _d.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
|
||||
if err != nil && sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
_d.mutation.done = true
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// RolePermissionDeleteOne is the builder for deleting a single RolePermission entity.
|
||||
type RolePermissionDeleteOne struct {
|
||||
_d *RolePermissionDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the RolePermissionDelete builder.
|
||||
func (_d *RolePermissionDeleteOne) Where(ps ...predicate.RolePermission) *RolePermissionDeleteOne {
|
||||
_d._d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (_d *RolePermissionDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := _d._d.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{rolepermission.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *RolePermissionDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := _d.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
686
internal/ent/rolepermission_query.go
Normal file
686
internal/ent/rolepermission_query.go
Normal file
@@ -0,0 +1,686 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/permission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/rolepermission"
|
||||
)
|
||||
|
||||
// RolePermissionQuery is the builder for querying RolePermission entities.
|
||||
type RolePermissionQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []rolepermission.OrderOption
|
||||
inters []Interceptor
|
||||
predicates []predicate.RolePermission
|
||||
withRole *RoleQuery
|
||||
withPermission *PermissionQuery
|
||||
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 RolePermissionQuery builder.
|
||||
func (_q *RolePermissionQuery) Where(ps ...predicate.RolePermission) *RolePermissionQuery {
|
||||
_q.predicates = append(_q.predicates, ps...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
func (_q *RolePermissionQuery) Limit(limit int) *RolePermissionQuery {
|
||||
_q.ctx.Limit = &limit
|
||||
return _q
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
func (_q *RolePermissionQuery) Offset(offset int) *RolePermissionQuery {
|
||||
_q.ctx.Offset = &offset
|
||||
return _q
|
||||
}
|
||||
|
||||
// Unique configures the query builder to filter duplicate records on query.
|
||||
// By default, unique is set to true, and can be disabled using this method.
|
||||
func (_q *RolePermissionQuery) Unique(unique bool) *RolePermissionQuery {
|
||||
_q.ctx.Unique = &unique
|
||||
return _q
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
func (_q *RolePermissionQuery) Order(o ...rolepermission.OrderOption) *RolePermissionQuery {
|
||||
_q.order = append(_q.order, o...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// QueryRole chains the current query on the "role" edge.
|
||||
func (_q *RolePermissionQuery) QueryRole() *RoleQuery {
|
||||
query := (&RoleClient{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(rolepermission.Table, rolepermission.FieldID, selector),
|
||||
sqlgraph.To(role.Table, role.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, false, rolepermission.RoleTable, rolepermission.RoleColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// QueryPermission chains the current query on the "permission" edge.
|
||||
func (_q *RolePermissionQuery) QueryPermission() *PermissionQuery {
|
||||
query := (&PermissionClient{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(rolepermission.Table, rolepermission.FieldID, selector),
|
||||
sqlgraph.To(permission.Table, permission.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, false, rolepermission.PermissionTable, rolepermission.PermissionColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// First returns the first RolePermission entity from the query.
|
||||
// Returns a *NotFoundError when no RolePermission was found.
|
||||
func (_q *RolePermissionQuery) First(ctx context.Context) (*RolePermission, error) {
|
||||
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nil, &NotFoundError{rolepermission.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (_q *RolePermissionQuery) FirstX(ctx context.Context) *RolePermission {
|
||||
node, err := _q.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first RolePermission ID from the query.
|
||||
// Returns a *NotFoundError when no RolePermission ID was found.
|
||||
func (_q *RolePermissionQuery) FirstID(ctx context.Context) (id int, err error) {
|
||||
var ids []int
|
||||
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &NotFoundError{rolepermission.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (_q *RolePermissionQuery) FirstIDX(ctx context.Context) int {
|
||||
id, err := _q.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single RolePermission entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when more than one RolePermission entity is found.
|
||||
// Returns a *NotFoundError when no RolePermission entities are found.
|
||||
func (_q *RolePermissionQuery) Only(ctx context.Context) (*RolePermission, error) {
|
||||
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch len(nodes) {
|
||||
case 1:
|
||||
return nodes[0], nil
|
||||
case 0:
|
||||
return nil, &NotFoundError{rolepermission.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{rolepermission.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (_q *RolePermissionQuery) OnlyX(ctx context.Context) *RolePermission {
|
||||
node, err := _q.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only RolePermission ID in the query.
|
||||
// Returns a *NotSingularError when more than one RolePermission ID is found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (_q *RolePermissionQuery) OnlyID(ctx context.Context) (id int, err error) {
|
||||
var ids []int
|
||||
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(ids) {
|
||||
case 1:
|
||||
id = ids[0]
|
||||
case 0:
|
||||
err = &NotFoundError{rolepermission.Label}
|
||||
default:
|
||||
err = &NotSingularError{rolepermission.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (_q *RolePermissionQuery) OnlyIDX(ctx context.Context) int {
|
||||
id, err := _q.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of RolePermissions.
|
||||
func (_q *RolePermissionQuery) All(ctx context.Context) ([]*RolePermission, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*RolePermission, *RolePermissionQuery]()
|
||||
return withInterceptors[[]*RolePermission](ctx, _q, qr, _q.inters)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (_q *RolePermissionQuery) AllX(ctx context.Context) []*RolePermission {
|
||||
nodes, err := _q.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of RolePermission IDs.
|
||||
func (_q *RolePermissionQuery) IDs(ctx context.Context) (ids []int, err error) {
|
||||
if _q.ctx.Unique == nil && _q.path != nil {
|
||||
_q.Unique(true)
|
||||
}
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
|
||||
if err = _q.Select(rolepermission.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (_q *RolePermissionQuery) IDsX(ctx context.Context) []int {
|
||||
ids, err := _q.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (_q *RolePermissionQuery) Count(ctx context.Context) (int, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return withInterceptors[int](ctx, _q, querierCount[*RolePermissionQuery](), _q.inters)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (_q *RolePermissionQuery) CountX(ctx context.Context) int {
|
||||
count, err := _q.Count(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// Exist returns true if the query has elements in the graph.
|
||||
func (_q *RolePermissionQuery) Exist(ctx context.Context) (bool, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
|
||||
switch _, err := _q.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExistX is like Exist, but panics if an error occurs.
|
||||
func (_q *RolePermissionQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := _q.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the RolePermissionQuery builder, including all associated steps. It can be
|
||||
// used to prepare common query builders and use them differently after the clone is made.
|
||||
func (_q *RolePermissionQuery) Clone() *RolePermissionQuery {
|
||||
if _q == nil {
|
||||
return nil
|
||||
}
|
||||
return &RolePermissionQuery{
|
||||
config: _q.config,
|
||||
ctx: _q.ctx.Clone(),
|
||||
order: append([]rolepermission.OrderOption{}, _q.order...),
|
||||
inters: append([]Interceptor{}, _q.inters...),
|
||||
predicates: append([]predicate.RolePermission{}, _q.predicates...),
|
||||
withRole: _q.withRole.Clone(),
|
||||
withPermission: _q.withPermission.Clone(),
|
||||
// clone intermediate query.
|
||||
sql: _q.sql.Clone(),
|
||||
path: _q.path,
|
||||
}
|
||||
}
|
||||
|
||||
// WithRole tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "role" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *RolePermissionQuery) WithRole(opts ...func(*RoleQuery)) *RolePermissionQuery {
|
||||
query := (&RoleClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withRole = query
|
||||
return _q
|
||||
}
|
||||
|
||||
// WithPermission tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "permission" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *RolePermissionQuery) WithPermission(opts ...func(*PermissionQuery)) *RolePermissionQuery {
|
||||
query := (&PermissionClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withPermission = query
|
||||
return _q
|
||||
}
|
||||
|
||||
// GroupBy is used to group vertices by one or more fields/columns.
|
||||
// It is often used with aggregate functions, like: count, max, mean, min, sum.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// RoleID string `json:"role_id,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.RolePermission.Query().
|
||||
// GroupBy(rolepermission.FieldRoleID).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *RolePermissionQuery) GroupBy(field string, fields ...string) *RolePermissionGroupBy {
|
||||
_q.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &RolePermissionGroupBy{build: _q}
|
||||
grbuild.flds = &_q.ctx.Fields
|
||||
grbuild.label = rolepermission.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 {
|
||||
// RoleID string `json:"role_id,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.RolePermission.Query().
|
||||
// Select(rolepermission.FieldRoleID).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *RolePermissionQuery) Select(fields ...string) *RolePermissionSelect {
|
||||
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
|
||||
sbuild := &RolePermissionSelect{RolePermissionQuery: _q}
|
||||
sbuild.label = rolepermission.Label
|
||||
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a RolePermissionSelect configured with the given aggregations.
|
||||
func (_q *RolePermissionQuery) Aggregate(fns ...AggregateFunc) *RolePermissionSelect {
|
||||
return _q.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (_q *RolePermissionQuery) prepareQuery(ctx context.Context) error {
|
||||
for _, inter := range _q.inters {
|
||||
if inter == nil {
|
||||
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
|
||||
}
|
||||
if trv, ok := inter.(Traverser); ok {
|
||||
if err := trv.Traverse(ctx, _q); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range _q.ctx.Fields {
|
||||
if !rolepermission.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
}
|
||||
if _q.path != nil {
|
||||
prev, err := _q.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_q.sql = prev
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *RolePermissionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*RolePermission, error) {
|
||||
var (
|
||||
nodes = []*RolePermission{}
|
||||
withFKs = _q.withFKs
|
||||
_spec = _q.querySpec()
|
||||
loadedTypes = [2]bool{
|
||||
_q.withRole != nil,
|
||||
_q.withPermission != nil,
|
||||
}
|
||||
)
|
||||
if withFKs {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, rolepermission.ForeignKeys...)
|
||||
}
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*RolePermission).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &RolePermission{config: _q.config}
|
||||
nodes = append(nodes, node)
|
||||
node.Edges.loadedTypes = loadedTypes
|
||||
return node.assignValues(columns, values)
|
||||
}
|
||||
for i := range hooks {
|
||||
hooks[i](ctx, _spec)
|
||||
}
|
||||
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nodes, nil
|
||||
}
|
||||
if query := _q.withRole; query != nil {
|
||||
if err := _q.loadRole(ctx, query, nodes, nil,
|
||||
func(n *RolePermission, e *Role) { n.Edges.Role = e }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if query := _q.withPermission; query != nil {
|
||||
if err := _q.loadPermission(ctx, query, nodes, nil,
|
||||
func(n *RolePermission, e *Permission) { n.Edges.Permission = e }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (_q *RolePermissionQuery) loadRole(ctx context.Context, query *RoleQuery, nodes []*RolePermission, init func(*RolePermission), assign func(*RolePermission, *Role)) error {
|
||||
ids := make([]string, 0, len(nodes))
|
||||
nodeids := make(map[string][]*RolePermission)
|
||||
for i := range nodes {
|
||||
fk := nodes[i].RoleID
|
||||
if _, ok := nodeids[fk]; !ok {
|
||||
ids = append(ids, fk)
|
||||
}
|
||||
nodeids[fk] = append(nodeids[fk], nodes[i])
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
query.Where(role.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 "role_id" returned %v`, n.ID)
|
||||
}
|
||||
for i := range nodes {
|
||||
assign(nodes[i], n)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (_q *RolePermissionQuery) loadPermission(ctx context.Context, query *PermissionQuery, nodes []*RolePermission, init func(*RolePermission), assign func(*RolePermission, *Permission)) error {
|
||||
ids := make([]string, 0, len(nodes))
|
||||
nodeids := make(map[string][]*RolePermission)
|
||||
for i := range nodes {
|
||||
fk := nodes[i].PermissionID
|
||||
if _, ok := nodeids[fk]; !ok {
|
||||
ids = append(ids, fk)
|
||||
}
|
||||
nodeids[fk] = append(nodeids[fk], nodes[i])
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
query.Where(permission.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 "permission_id" returned %v`, n.ID)
|
||||
}
|
||||
for i := range nodes {
|
||||
assign(nodes[i], n)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *RolePermissionQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := _q.querySpec()
|
||||
_spec.Node.Columns = _q.ctx.Fields
|
||||
if len(_q.ctx.Fields) > 0 {
|
||||
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
|
||||
}
|
||||
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
|
||||
}
|
||||
|
||||
func (_q *RolePermissionQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := sqlgraph.NewQuerySpec(rolepermission.Table, rolepermission.Columns, sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt))
|
||||
_spec.From = _q.sql
|
||||
if unique := _q.ctx.Unique; unique != nil {
|
||||
_spec.Unique = *unique
|
||||
} else if _q.path != nil {
|
||||
_spec.Unique = true
|
||||
}
|
||||
if fields := _q.ctx.Fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, rolepermission.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != rolepermission.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
if _q.withRole != nil {
|
||||
_spec.Node.AddColumnOnce(rolepermission.FieldRoleID)
|
||||
}
|
||||
if _q.withPermission != nil {
|
||||
_spec.Node.AddColumnOnce(rolepermission.FieldPermissionID)
|
||||
}
|
||||
}
|
||||
if ps := _q.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit := _q.ctx.Limit; limit != nil {
|
||||
_spec.Limit = *limit
|
||||
}
|
||||
if offset := _q.ctx.Offset; offset != nil {
|
||||
_spec.Offset = *offset
|
||||
}
|
||||
if ps := _q.order; len(ps) > 0 {
|
||||
_spec.Order = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
return _spec
|
||||
}
|
||||
|
||||
func (_q *RolePermissionQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(_q.driver.Dialect())
|
||||
t1 := builder.Table(rolepermission.Table)
|
||||
columns := _q.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = rolepermission.Columns
|
||||
}
|
||||
selector := builder.Select(t1.Columns(columns...)...).From(t1)
|
||||
if _q.sql != nil {
|
||||
selector = _q.sql
|
||||
selector.Select(selector.Columns(columns...)...)
|
||||
}
|
||||
if _q.ctx.Unique != nil && *_q.ctx.Unique {
|
||||
selector.Distinct()
|
||||
}
|
||||
for _, p := range _q.predicates {
|
||||
p(selector)
|
||||
}
|
||||
for _, p := range _q.order {
|
||||
p(selector)
|
||||
}
|
||||
if offset := _q.ctx.Offset; offset != nil {
|
||||
// limit is mandatory for offset clause. We start
|
||||
// with default value, and override it below if needed.
|
||||
selector.Offset(*offset).Limit(math.MaxInt32)
|
||||
}
|
||||
if limit := _q.ctx.Limit; limit != nil {
|
||||
selector.Limit(*limit)
|
||||
}
|
||||
return selector
|
||||
}
|
||||
|
||||
// RolePermissionGroupBy is the group-by builder for RolePermission entities.
|
||||
type RolePermissionGroupBy struct {
|
||||
selector
|
||||
build *RolePermissionQuery
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (_g *RolePermissionGroupBy) Aggregate(fns ...AggregateFunc) *RolePermissionGroupBy {
|
||||
_g.fns = append(_g.fns, fns...)
|
||||
return _g
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_g *RolePermissionGroupBy) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
|
||||
if err := _g.build.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*RolePermissionQuery, *RolePermissionGroupBy](ctx, _g.build, _g, _g.build.inters, v)
|
||||
}
|
||||
|
||||
func (_g *RolePermissionGroupBy) sqlScan(ctx context.Context, root *RolePermissionQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx).Select()
|
||||
aggregation := make([]string, 0, len(_g.fns))
|
||||
for _, fn := range _g.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
|
||||
for _, f := range *_g.flds {
|
||||
columns = append(columns, selector.C(f))
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
selector.GroupBy(selector.Columns(*_g.flds...)...)
|
||||
if err := selector.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
// RolePermissionSelect is the builder for selecting fields of RolePermission entities.
|
||||
type RolePermissionSelect struct {
|
||||
*RolePermissionQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (_s *RolePermissionSelect) Aggregate(fns ...AggregateFunc) *RolePermissionSelect {
|
||||
_s.fns = append(_s.fns, fns...)
|
||||
return _s
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_s *RolePermissionSelect) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
|
||||
if err := _s.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*RolePermissionQuery, *RolePermissionSelect](ctx, _s.RolePermissionQuery, _s, _s.inters, v)
|
||||
}
|
||||
|
||||
func (_s *RolePermissionSelect) sqlScan(ctx context.Context, root *RolePermissionQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx)
|
||||
aggregation := make([]string, 0, len(_s.fns))
|
||||
for _, fn := range _s.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
switch n := len(*_s.selector.flds); {
|
||||
case n == 0 && len(aggregation) > 0:
|
||||
selector.Select(aggregation...)
|
||||
case n != 0 && len(aggregation) > 0:
|
||||
selector.AppendSelect(aggregation...)
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
421
internal/ent/rolepermission_update.go
Normal file
421
internal/ent/rolepermission_update.go
Normal file
@@ -0,0 +1,421 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/permission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/rolepermission"
|
||||
)
|
||||
|
||||
// RolePermissionUpdate is the builder for updating RolePermission entities.
|
||||
type RolePermissionUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *RolePermissionMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the RolePermissionUpdate builder.
|
||||
func (_u *RolePermissionUpdate) Where(ps ...predicate.RolePermission) *RolePermissionUpdate {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetRoleID sets the "role_id" field.
|
||||
func (_u *RolePermissionUpdate) SetRoleID(v string) *RolePermissionUpdate {
|
||||
_u.mutation.SetRoleID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableRoleID sets the "role_id" field if the given value is not nil.
|
||||
func (_u *RolePermissionUpdate) SetNillableRoleID(v *string) *RolePermissionUpdate {
|
||||
if v != nil {
|
||||
_u.SetRoleID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetPermissionID sets the "permission_id" field.
|
||||
func (_u *RolePermissionUpdate) SetPermissionID(v string) *RolePermissionUpdate {
|
||||
_u.mutation.SetPermissionID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillablePermissionID sets the "permission_id" field if the given value is not nil.
|
||||
func (_u *RolePermissionUpdate) SetNillablePermissionID(v *string) *RolePermissionUpdate {
|
||||
if v != nil {
|
||||
_u.SetPermissionID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetRole sets the "role" edge to the Role entity.
|
||||
func (_u *RolePermissionUpdate) SetRole(v *Role) *RolePermissionUpdate {
|
||||
return _u.SetRoleID(v.ID)
|
||||
}
|
||||
|
||||
// SetPermission sets the "permission" edge to the Permission entity.
|
||||
func (_u *RolePermissionUpdate) SetPermission(v *Permission) *RolePermissionUpdate {
|
||||
return _u.SetPermissionID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the RolePermissionMutation object of the builder.
|
||||
func (_u *RolePermissionUpdate) Mutation() *RolePermissionMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearRole clears the "role" edge to the Role entity.
|
||||
func (_u *RolePermissionUpdate) ClearRole() *RolePermissionUpdate {
|
||||
_u.mutation.ClearRole()
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearPermission clears the "permission" edge to the Permission entity.
|
||||
func (_u *RolePermissionUpdate) ClearPermission() *RolePermissionUpdate {
|
||||
_u.mutation.ClearPermission()
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (_u *RolePermissionUpdate) Save(ctx context.Context) (int, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *RolePermissionUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_u *RolePermissionUpdate) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *RolePermissionUpdate) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *RolePermissionUpdate) check() error {
|
||||
if _u.mutation.RoleCleared() && len(_u.mutation.RoleIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "RolePermission.role"`)
|
||||
}
|
||||
if _u.mutation.PermissionCleared() && len(_u.mutation.PermissionIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "RolePermission.permission"`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *RolePermissionUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(rolepermission.Table, rolepermission.Columns, sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt))
|
||||
if ps := _u.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if _u.mutation.RoleCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: rolepermission.RoleTable,
|
||||
Columns: []string{rolepermission.RoleColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RoleIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: rolepermission.RoleTable,
|
||||
Columns: []string{rolepermission.RoleColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.PermissionCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: rolepermission.PermissionTable,
|
||||
Columns: []string{rolepermission.PermissionColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.PermissionIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: rolepermission.PermissionTable,
|
||||
Columns: []string{rolepermission.PermissionColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
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{rolepermission.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
// RolePermissionUpdateOne is the builder for updating a single RolePermission entity.
|
||||
type RolePermissionUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *RolePermissionMutation
|
||||
}
|
||||
|
||||
// SetRoleID sets the "role_id" field.
|
||||
func (_u *RolePermissionUpdateOne) SetRoleID(v string) *RolePermissionUpdateOne {
|
||||
_u.mutation.SetRoleID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableRoleID sets the "role_id" field if the given value is not nil.
|
||||
func (_u *RolePermissionUpdateOne) SetNillableRoleID(v *string) *RolePermissionUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetRoleID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetPermissionID sets the "permission_id" field.
|
||||
func (_u *RolePermissionUpdateOne) SetPermissionID(v string) *RolePermissionUpdateOne {
|
||||
_u.mutation.SetPermissionID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillablePermissionID sets the "permission_id" field if the given value is not nil.
|
||||
func (_u *RolePermissionUpdateOne) SetNillablePermissionID(v *string) *RolePermissionUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetPermissionID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetRole sets the "role" edge to the Role entity.
|
||||
func (_u *RolePermissionUpdateOne) SetRole(v *Role) *RolePermissionUpdateOne {
|
||||
return _u.SetRoleID(v.ID)
|
||||
}
|
||||
|
||||
// SetPermission sets the "permission" edge to the Permission entity.
|
||||
func (_u *RolePermissionUpdateOne) SetPermission(v *Permission) *RolePermissionUpdateOne {
|
||||
return _u.SetPermissionID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the RolePermissionMutation object of the builder.
|
||||
func (_u *RolePermissionUpdateOne) Mutation() *RolePermissionMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearRole clears the "role" edge to the Role entity.
|
||||
func (_u *RolePermissionUpdateOne) ClearRole() *RolePermissionUpdateOne {
|
||||
_u.mutation.ClearRole()
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearPermission clears the "permission" edge to the Permission entity.
|
||||
func (_u *RolePermissionUpdateOne) ClearPermission() *RolePermissionUpdateOne {
|
||||
_u.mutation.ClearPermission()
|
||||
return _u
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the RolePermissionUpdate builder.
|
||||
func (_u *RolePermissionUpdateOne) Where(ps ...predicate.RolePermission) *RolePermissionUpdateOne {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Select allows selecting one or more fields (columns) of the returned entity.
|
||||
// The default is selecting all fields defined in the entity schema.
|
||||
func (_u *RolePermissionUpdateOne) Select(field string, fields ...string) *RolePermissionUpdateOne {
|
||||
_u.fields = append([]string{field}, fields...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated RolePermission entity.
|
||||
func (_u *RolePermissionUpdateOne) Save(ctx context.Context) (*RolePermission, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *RolePermissionUpdateOne) SaveX(ctx context.Context) *RolePermission {
|
||||
node, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (_u *RolePermissionUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *RolePermissionUpdateOne) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *RolePermissionUpdateOne) check() error {
|
||||
if _u.mutation.RoleCleared() && len(_u.mutation.RoleIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "RolePermission.role"`)
|
||||
}
|
||||
if _u.mutation.PermissionCleared() && len(_u.mutation.PermissionIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "RolePermission.permission"`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *RolePermissionUpdateOne) sqlSave(ctx context.Context) (_node *RolePermission, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(rolepermission.Table, rolepermission.Columns, sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt))
|
||||
id, ok := _u.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "RolePermission.id" for update`)}
|
||||
}
|
||||
_spec.Node.ID.Value = id
|
||||
if fields := _u.fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, rolepermission.FieldID)
|
||||
for _, f := range fields {
|
||||
if !rolepermission.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != rolepermission.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := _u.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if _u.mutation.RoleCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: rolepermission.RoleTable,
|
||||
Columns: []string{rolepermission.RoleColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RoleIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: rolepermission.RoleTable,
|
||||
Columns: []string{rolepermission.RoleColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.PermissionCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: rolepermission.PermissionTable,
|
||||
Columns: []string{rolepermission.PermissionColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.PermissionIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: rolepermission.PermissionTable,
|
||||
Columns: []string{rolepermission.PermissionColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
_node = &RolePermission{config: _u.config}
|
||||
_spec.Assign = _node.assignValues
|
||||
_spec.ScanValues = _node.scanValues
|
||||
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{rolepermission.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
73
internal/ent/runtime.go
Normal file
73
internal/ent/runtime.go
Normal file
@@ -0,0 +1,73 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/auditlog"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/permission"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/schema"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/user"
|
||||
)
|
||||
|
||||
// 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() {
|
||||
auditlogFields := schema.AuditLog{}.Fields()
|
||||
_ = auditlogFields
|
||||
// auditlogDescActorID is the schema descriptor for actor_id field.
|
||||
auditlogDescActorID := auditlogFields[1].Descriptor()
|
||||
// auditlog.ActorIDValidator is a validator for the "actor_id" field. It is called by the builders before save.
|
||||
auditlog.ActorIDValidator = auditlogDescActorID.Validators[0].(func(string) error)
|
||||
// auditlogDescAction is the schema descriptor for action field.
|
||||
auditlogDescAction := auditlogFields[2].Descriptor()
|
||||
// auditlog.ActionValidator is a validator for the "action" field. It is called by the builders before save.
|
||||
auditlog.ActionValidator = auditlogDescAction.Validators[0].(func(string) error)
|
||||
// auditlogDescTimestamp is the schema descriptor for timestamp field.
|
||||
auditlogDescTimestamp := auditlogFields[5].Descriptor()
|
||||
// auditlog.DefaultTimestamp holds the default value on creation for the timestamp field.
|
||||
auditlog.DefaultTimestamp = auditlogDescTimestamp.Default.(func() time.Time)
|
||||
permissionFields := schema.Permission{}.Fields()
|
||||
_ = permissionFields
|
||||
// permissionDescName is the schema descriptor for name field.
|
||||
permissionDescName := permissionFields[1].Descriptor()
|
||||
// permission.NameValidator is a validator for the "name" field. It is called by the builders before save.
|
||||
permission.NameValidator = permissionDescName.Validators[0].(func(string) error)
|
||||
roleFields := schema.Role{}.Fields()
|
||||
_ = roleFields
|
||||
// roleDescName is the schema descriptor for name field.
|
||||
roleDescName := roleFields[1].Descriptor()
|
||||
// role.NameValidator is a validator for the "name" field. It is called by the builders before save.
|
||||
role.NameValidator = roleDescName.Validators[0].(func(string) error)
|
||||
// roleDescCreatedAt is the schema descriptor for created_at field.
|
||||
roleDescCreatedAt := roleFields[3].Descriptor()
|
||||
// role.DefaultCreatedAt holds the default value on creation for the created_at field.
|
||||
role.DefaultCreatedAt = roleDescCreatedAt.Default.(func() time.Time)
|
||||
userFields := schema.User{}.Fields()
|
||||
_ = userFields
|
||||
// userDescEmail is the schema descriptor for email field.
|
||||
userDescEmail := userFields[1].Descriptor()
|
||||
// user.EmailValidator is a validator for the "email" field. It is called by the builders before save.
|
||||
user.EmailValidator = userDescEmail.Validators[0].(func(string) error)
|
||||
// userDescPasswordHash is the schema descriptor for password_hash field.
|
||||
userDescPasswordHash := userFields[2].Descriptor()
|
||||
// user.PasswordHashValidator is a validator for the "password_hash" field. It is called by the builders before save.
|
||||
user.PasswordHashValidator = userDescPasswordHash.Validators[0].(func(string) error)
|
||||
// userDescVerified is the schema descriptor for verified field.
|
||||
userDescVerified := userFields[3].Descriptor()
|
||||
// user.DefaultVerified holds the default value on creation for the verified field.
|
||||
user.DefaultVerified = userDescVerified.Default.(bool)
|
||||
// userDescCreatedAt is the schema descriptor for created_at field.
|
||||
userDescCreatedAt := userFields[4].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[5].Descriptor()
|
||||
// user.DefaultUpdatedAt holds the default value on creation for the updated_at field.
|
||||
user.DefaultUpdatedAt = userDescUpdatedAt.Default.(func() time.Time)
|
||||
// user.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
|
||||
user.UpdateDefaultUpdatedAt = userDescUpdatedAt.UpdateDefault.(func() time.Time)
|
||||
}
|
||||
10
internal/ent/runtime/runtime.go
Normal file
10
internal/ent/runtime/runtime.go
Normal file
@@ -0,0 +1,10 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package runtime
|
||||
|
||||
// The schema-stitching logic is generated in git.dcentral.systems/toolz/goplt/internal/ent/runtime.go
|
||||
|
||||
const (
|
||||
Version = "v0.14.5" // Version of ent codegen.
|
||||
Sum = "h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=" // Sum of ent codegen.
|
||||
)
|
||||
49
internal/ent/schema/audit_log.go
Normal file
49
internal/ent/schema/audit_log.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/schema/field"
|
||||
"entgo.io/ent/schema/index"
|
||||
)
|
||||
|
||||
// AuditLog holds the schema definition for the AuditLog entity.
|
||||
type AuditLog struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
// Fields of the AuditLog.
|
||||
func (AuditLog) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.String("id").
|
||||
Unique().
|
||||
Immutable(),
|
||||
field.String("actor_id").
|
||||
NotEmpty().
|
||||
Comment("ID of the user/actor performing the action"),
|
||||
field.String("action").
|
||||
NotEmpty().
|
||||
Comment("Action performed (e.g., create, update, delete)"),
|
||||
field.String("target_id").
|
||||
Optional().
|
||||
Comment("ID of the target resource"),
|
||||
field.JSON("metadata", map[string]interface{}{}).
|
||||
Optional().
|
||||
Comment("Additional metadata as JSON"),
|
||||
field.Time("timestamp").
|
||||
Default(time.Now).
|
||||
Immutable(),
|
||||
}
|
||||
}
|
||||
|
||||
// Indexes of the AuditLog.
|
||||
func (AuditLog) Indexes() []ent.Index {
|
||||
return []ent.Index{
|
||||
index.Fields("actor_id"),
|
||||
index.Fields("target_id"),
|
||||
index.Fields("timestamp"),
|
||||
index.Fields("action"),
|
||||
}
|
||||
}
|
||||
|
||||
33
internal/ent/schema/permission.go
Normal file
33
internal/ent/schema/permission.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/schema/edge"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// Permission holds the schema definition for the Permission entity.
|
||||
type Permission struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
// Fields of the Permission.
|
||||
func (Permission) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.String("id").
|
||||
Unique().
|
||||
Immutable(),
|
||||
field.String("name").
|
||||
Unique().
|
||||
NotEmpty().
|
||||
Comment("Format: module.resource.action"),
|
||||
}
|
||||
}
|
||||
|
||||
// Edges of the Permission.
|
||||
func (Permission) Edges() []ent.Edge {
|
||||
return []ent.Edge{
|
||||
edge.To("role_permissions", RolePermission.Type),
|
||||
}
|
||||
}
|
||||
|
||||
40
internal/ent/schema/role.go
Normal file
40
internal/ent/schema/role.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/schema/edge"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// Role holds the schema definition for the Role entity.
|
||||
type Role struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
// Fields of the Role.
|
||||
func (Role) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.String("id").
|
||||
Unique().
|
||||
Immutable(),
|
||||
field.String("name").
|
||||
Unique().
|
||||
NotEmpty(),
|
||||
field.String("description").
|
||||
Optional(),
|
||||
field.Time("created_at").
|
||||
Default(time.Now).
|
||||
Immutable(),
|
||||
}
|
||||
}
|
||||
|
||||
// Edges of the Role.
|
||||
func (Role) Edges() []ent.Edge {
|
||||
return []ent.Edge{
|
||||
edge.To("role_permissions", RolePermission.Type),
|
||||
edge.To("user_roles", UserRole.Type),
|
||||
}
|
||||
}
|
||||
|
||||
35
internal/ent/schema/role_permission.go
Normal file
35
internal/ent/schema/role_permission.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/schema/edge"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// RolePermission holds the schema definition for the RolePermission entity (many-to-many relationship).
|
||||
type RolePermission struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
// Fields of the RolePermission.
|
||||
func (RolePermission) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.String("role_id"),
|
||||
field.String("permission_id"),
|
||||
}
|
||||
}
|
||||
|
||||
// Edges of the RolePermission.
|
||||
func (RolePermission) Edges() []ent.Edge {
|
||||
return []ent.Edge{
|
||||
edge.To("role", Role.Type).
|
||||
Unique().
|
||||
Required().
|
||||
Field("role_id"),
|
||||
edge.To("permission", Permission.Type).
|
||||
Unique().
|
||||
Required().
|
||||
Field("permission_id"),
|
||||
}
|
||||
}
|
||||
|
||||
44
internal/ent/schema/user.go
Normal file
44
internal/ent/schema/user.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/schema/edge"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// User holds the schema definition for the User entity.
|
||||
type User struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
// Fields of the User.
|
||||
func (User) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.String("id").
|
||||
Unique().
|
||||
Immutable(),
|
||||
field.String("email").
|
||||
Unique().
|
||||
NotEmpty(),
|
||||
field.String("password_hash").
|
||||
NotEmpty(),
|
||||
field.Bool("verified").
|
||||
Default(false),
|
||||
field.Time("created_at").
|
||||
Default(time.Now).
|
||||
Immutable(),
|
||||
field.Time("updated_at").
|
||||
Default(time.Now).
|
||||
UpdateDefault(time.Now),
|
||||
}
|
||||
}
|
||||
|
||||
// Edges of the User.
|
||||
func (User) Edges() []ent.Edge {
|
||||
return []ent.Edge{
|
||||
edge.To("user_roles", UserRole.Type),
|
||||
}
|
||||
}
|
||||
|
||||
35
internal/ent/schema/user_role.go
Normal file
35
internal/ent/schema/user_role.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/schema/edge"
|
||||
"entgo.io/ent/schema/field"
|
||||
)
|
||||
|
||||
// UserRole holds the schema definition for the UserRole entity (many-to-many relationship).
|
||||
type UserRole struct {
|
||||
ent.Schema
|
||||
}
|
||||
|
||||
// Fields of the UserRole.
|
||||
func (UserRole) Fields() []ent.Field {
|
||||
return []ent.Field{
|
||||
field.String("user_id"),
|
||||
field.String("role_id"),
|
||||
}
|
||||
}
|
||||
|
||||
// Edges of the UserRole.
|
||||
func (UserRole) Edges() []ent.Edge {
|
||||
return []ent.Edge{
|
||||
edge.To("user", User.Type).
|
||||
Unique().
|
||||
Required().
|
||||
Field("user_id"),
|
||||
edge.To("role", Role.Type).
|
||||
Unique().
|
||||
Required().
|
||||
Field("role_id"),
|
||||
}
|
||||
}
|
||||
|
||||
225
internal/ent/tx.go
Normal file
225
internal/ent/tx.go
Normal file
@@ -0,0 +1,225 @@
|
||||
// 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
|
||||
// AuditLog is the client for interacting with the AuditLog builders.
|
||||
AuditLog *AuditLogClient
|
||||
// Permission is the client for interacting with the Permission builders.
|
||||
Permission *PermissionClient
|
||||
// Role is the client for interacting with the Role builders.
|
||||
Role *RoleClient
|
||||
// RolePermission is the client for interacting with the RolePermission builders.
|
||||
RolePermission *RolePermissionClient
|
||||
// User is the client for interacting with the User builders.
|
||||
User *UserClient
|
||||
// UserRole is the client for interacting with the UserRole builders.
|
||||
UserRole *UserRoleClient
|
||||
|
||||
// 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.AuditLog = NewAuditLogClient(tx.config)
|
||||
tx.Permission = NewPermissionClient(tx.config)
|
||||
tx.Role = NewRoleClient(tx.config)
|
||||
tx.RolePermission = NewRolePermissionClient(tx.config)
|
||||
tx.User = NewUserClient(tx.config)
|
||||
tx.UserRole = NewUserRoleClient(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: AuditLog.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)
|
||||
176
internal/ent/user.go
Normal file
176
internal/ent/user.go
Normal file
@@ -0,0 +1,176 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/user"
|
||||
)
|
||||
|
||||
// User is the model entity for the User schema.
|
||||
type User struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID string `json:"id,omitempty"`
|
||||
// Email holds the value of the "email" field.
|
||||
Email string `json:"email,omitempty"`
|
||||
// PasswordHash holds the value of the "password_hash" field.
|
||||
PasswordHash string `json:"password_hash,omitempty"`
|
||||
// Verified holds the value of the "verified" field.
|
||||
Verified bool `json:"verified,omitempty"`
|
||||
// CreatedAt holds the value of the "created_at" field.
|
||||
CreatedAt time.Time `json:"created_at,omitempty"`
|
||||
// UpdatedAt holds the value of the "updated_at" field.
|
||||
UpdatedAt time.Time `json:"updated_at,omitempty"`
|
||||
// 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"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// UserEdges holds the relations/edges for other nodes in the graph.
|
||||
type UserEdges struct {
|
||||
// UserRoles holds the value of the user_roles edge.
|
||||
UserRoles []*UserRole `json:"user_roles,omitempty"`
|
||||
// loadedTypes holds the information for reporting if a
|
||||
// type was loaded (or requested) in eager-loading or not.
|
||||
loadedTypes [1]bool
|
||||
}
|
||||
|
||||
// UserRolesOrErr returns the UserRoles value or an error if the edge
|
||||
// was not loaded in eager-loading.
|
||||
func (e UserEdges) UserRolesOrErr() ([]*UserRole, error) {
|
||||
if e.loadedTypes[0] {
|
||||
return e.UserRoles, nil
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "user_roles"}
|
||||
}
|
||||
|
||||
// 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.FieldVerified:
|
||||
values[i] = new(sql.NullBool)
|
||||
case user.FieldID, user.FieldEmail, user.FieldPasswordHash:
|
||||
values[i] = new(sql.NullString)
|
||||
case user.FieldCreatedAt, user.FieldUpdatedAt:
|
||||
values[i] = new(sql.NullTime)
|
||||
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 (_m *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:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ID = value.String
|
||||
}
|
||||
case user.FieldEmail:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field email", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Email = value.String
|
||||
}
|
||||
case user.FieldPasswordHash:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field password_hash", values[i])
|
||||
} else if value.Valid {
|
||||
_m.PasswordHash = value.String
|
||||
}
|
||||
case user.FieldVerified:
|
||||
if value, ok := values[i].(*sql.NullBool); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field verified", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Verified = value.Bool
|
||||
}
|
||||
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 {
|
||||
_m.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 {
|
||||
_m.UpdatedAt = value.Time
|
||||
}
|
||||
default:
|
||||
_m.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 (_m *User) Value(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// QueryUserRoles queries the "user_roles" edge of the User entity.
|
||||
func (_m *User) QueryUserRoles() *UserRoleQuery {
|
||||
return NewUserClient(_m.config).QueryUserRoles(_m)
|
||||
}
|
||||
|
||||
// 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 (_m *User) Update() *UserUpdateOne {
|
||||
return NewUserClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// 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 (_m *User) Unwrap() *User {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: User is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *User) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("User(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
builder.WriteString("email=")
|
||||
builder.WriteString(_m.Email)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("password_hash=")
|
||||
builder.WriteString(_m.PasswordHash)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("verified=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Verified))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("created_at=")
|
||||
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("updated_at=")
|
||||
builder.WriteString(_m.UpdatedAt.Format(time.ANSIC))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// Users is a parsable slice of User.
|
||||
type Users []*User
|
||||
127
internal/ent/user/user.go
Normal file
127
internal/ent/user/user.go
Normal file
@@ -0,0 +1,127 @@
|
||||
// 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"
|
||||
// FieldEmail holds the string denoting the email field in the database.
|
||||
FieldEmail = "email"
|
||||
// FieldPasswordHash holds the string denoting the password_hash field in the database.
|
||||
FieldPasswordHash = "password_hash"
|
||||
// FieldVerified holds the string denoting the verified field in the database.
|
||||
FieldVerified = "verified"
|
||||
// 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"
|
||||
// EdgeUserRoles holds the string denoting the user_roles edge name in mutations.
|
||||
EdgeUserRoles = "user_roles"
|
||||
// Table holds the table name of the user in the database.
|
||||
Table = "users"
|
||||
// UserRolesTable is the table that holds the user_roles relation/edge.
|
||||
UserRolesTable = "user_roles"
|
||||
// UserRolesInverseTable is the table name for the UserRole entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "userrole" package.
|
||||
UserRolesInverseTable = "user_roles"
|
||||
// UserRolesColumn is the table column denoting the user_roles relation/edge.
|
||||
UserRolesColumn = "user_user_roles"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for user fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldEmail,
|
||||
FieldPasswordHash,
|
||||
FieldVerified,
|
||||
FieldCreatedAt,
|
||||
FieldUpdatedAt,
|
||||
}
|
||||
|
||||
// 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 (
|
||||
// EmailValidator is a validator for the "email" field. It is called by the builders before save.
|
||||
EmailValidator func(string) error
|
||||
// PasswordHashValidator is a validator for the "password_hash" field. It is called by the builders before save.
|
||||
PasswordHashValidator func(string) error
|
||||
// DefaultVerified holds the default value on creation for the "verified" field.
|
||||
DefaultVerified bool
|
||||
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
|
||||
DefaultCreatedAt func() time.Time
|
||||
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
|
||||
DefaultUpdatedAt func() time.Time
|
||||
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
|
||||
UpdateDefaultUpdatedAt func() time.Time
|
||||
)
|
||||
|
||||
// OrderOption defines the ordering options for the 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()
|
||||
}
|
||||
|
||||
// ByEmail orders the results by the email field.
|
||||
func ByEmail(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldEmail, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByPasswordHash orders the results by the password_hash field.
|
||||
func ByPasswordHash(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldPasswordHash, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByVerified orders the results by the verified field.
|
||||
func ByVerified(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldVerified, 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()
|
||||
}
|
||||
|
||||
// ByUserRolesCount orders the results by user_roles count.
|
||||
func ByUserRolesCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborsCount(s, newUserRolesStep(), opts...)
|
||||
}
|
||||
}
|
||||
|
||||
// ByUserRoles orders the results by user_roles terms.
|
||||
func ByUserRoles(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newUserRolesStep(), append([]sql.OrderTerm{term}, terms...)...)
|
||||
}
|
||||
}
|
||||
func newUserRolesStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(UserRolesInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, UserRolesTable, UserRolesColumn),
|
||||
)
|
||||
}
|
||||
349
internal/ent/user/where.go
Normal file
349
internal/ent/user/where.go
Normal file
@@ -0,0 +1,349 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package user
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id string) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id string) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id string) predicate.User {
|
||||
return predicate.User(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...string) predicate.User {
|
||||
return predicate.User(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...string) predicate.User {
|
||||
return predicate.User(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id string) predicate.User {
|
||||
return predicate.User(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id string) predicate.User {
|
||||
return predicate.User(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id string) predicate.User {
|
||||
return predicate.User(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id string) predicate.User {
|
||||
return predicate.User(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEqualFold applies the EqualFold predicate on the ID field.
|
||||
func IDEqualFold(id string) predicate.User {
|
||||
return predicate.User(sql.FieldEqualFold(FieldID, id))
|
||||
}
|
||||
|
||||
// IDContainsFold applies the ContainsFold predicate on the ID field.
|
||||
func IDContainsFold(id string) predicate.User {
|
||||
return predicate.User(sql.FieldContainsFold(FieldID, id))
|
||||
}
|
||||
|
||||
// Email applies equality check predicate on the "email" field. It's identical to EmailEQ.
|
||||
func Email(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldEmail, v))
|
||||
}
|
||||
|
||||
// PasswordHash applies equality check predicate on the "password_hash" field. It's identical to PasswordHashEQ.
|
||||
func PasswordHash(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldPasswordHash, v))
|
||||
}
|
||||
|
||||
// Verified applies equality check predicate on the "verified" field. It's identical to VerifiedEQ.
|
||||
func Verified(v bool) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldVerified, v))
|
||||
}
|
||||
|
||||
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
|
||||
func CreatedAt(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
|
||||
func UpdatedAt(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// EmailEQ applies the EQ predicate on the "email" field.
|
||||
func EmailEQ(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldEmail, v))
|
||||
}
|
||||
|
||||
// EmailNEQ applies the NEQ predicate on the "email" field.
|
||||
func EmailNEQ(v string) predicate.User {
|
||||
return predicate.User(sql.FieldNEQ(FieldEmail, v))
|
||||
}
|
||||
|
||||
// EmailIn applies the In predicate on the "email" field.
|
||||
func EmailIn(vs ...string) predicate.User {
|
||||
return predicate.User(sql.FieldIn(FieldEmail, vs...))
|
||||
}
|
||||
|
||||
// EmailNotIn applies the NotIn predicate on the "email" field.
|
||||
func EmailNotIn(vs ...string) predicate.User {
|
||||
return predicate.User(sql.FieldNotIn(FieldEmail, vs...))
|
||||
}
|
||||
|
||||
// EmailGT applies the GT predicate on the "email" field.
|
||||
func EmailGT(v string) predicate.User {
|
||||
return predicate.User(sql.FieldGT(FieldEmail, v))
|
||||
}
|
||||
|
||||
// EmailGTE applies the GTE predicate on the "email" field.
|
||||
func EmailGTE(v string) predicate.User {
|
||||
return predicate.User(sql.FieldGTE(FieldEmail, v))
|
||||
}
|
||||
|
||||
// EmailLT applies the LT predicate on the "email" field.
|
||||
func EmailLT(v string) predicate.User {
|
||||
return predicate.User(sql.FieldLT(FieldEmail, v))
|
||||
}
|
||||
|
||||
// EmailLTE applies the LTE predicate on the "email" field.
|
||||
func EmailLTE(v string) predicate.User {
|
||||
return predicate.User(sql.FieldLTE(FieldEmail, v))
|
||||
}
|
||||
|
||||
// EmailContains applies the Contains predicate on the "email" field.
|
||||
func EmailContains(v string) predicate.User {
|
||||
return predicate.User(sql.FieldContains(FieldEmail, v))
|
||||
}
|
||||
|
||||
// EmailHasPrefix applies the HasPrefix predicate on the "email" field.
|
||||
func EmailHasPrefix(v string) predicate.User {
|
||||
return predicate.User(sql.FieldHasPrefix(FieldEmail, v))
|
||||
}
|
||||
|
||||
// EmailHasSuffix applies the HasSuffix predicate on the "email" field.
|
||||
func EmailHasSuffix(v string) predicate.User {
|
||||
return predicate.User(sql.FieldHasSuffix(FieldEmail, v))
|
||||
}
|
||||
|
||||
// EmailEqualFold applies the EqualFold predicate on the "email" field.
|
||||
func EmailEqualFold(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEqualFold(FieldEmail, v))
|
||||
}
|
||||
|
||||
// EmailContainsFold applies the ContainsFold predicate on the "email" field.
|
||||
func EmailContainsFold(v string) predicate.User {
|
||||
return predicate.User(sql.FieldContainsFold(FieldEmail, v))
|
||||
}
|
||||
|
||||
// PasswordHashEQ applies the EQ predicate on the "password_hash" field.
|
||||
func PasswordHashEQ(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldPasswordHash, v))
|
||||
}
|
||||
|
||||
// PasswordHashNEQ applies the NEQ predicate on the "password_hash" field.
|
||||
func PasswordHashNEQ(v string) predicate.User {
|
||||
return predicate.User(sql.FieldNEQ(FieldPasswordHash, v))
|
||||
}
|
||||
|
||||
// PasswordHashIn applies the In predicate on the "password_hash" field.
|
||||
func PasswordHashIn(vs ...string) predicate.User {
|
||||
return predicate.User(sql.FieldIn(FieldPasswordHash, vs...))
|
||||
}
|
||||
|
||||
// PasswordHashNotIn applies the NotIn predicate on the "password_hash" field.
|
||||
func PasswordHashNotIn(vs ...string) predicate.User {
|
||||
return predicate.User(sql.FieldNotIn(FieldPasswordHash, vs...))
|
||||
}
|
||||
|
||||
// PasswordHashGT applies the GT predicate on the "password_hash" field.
|
||||
func PasswordHashGT(v string) predicate.User {
|
||||
return predicate.User(sql.FieldGT(FieldPasswordHash, v))
|
||||
}
|
||||
|
||||
// PasswordHashGTE applies the GTE predicate on the "password_hash" field.
|
||||
func PasswordHashGTE(v string) predicate.User {
|
||||
return predicate.User(sql.FieldGTE(FieldPasswordHash, v))
|
||||
}
|
||||
|
||||
// PasswordHashLT applies the LT predicate on the "password_hash" field.
|
||||
func PasswordHashLT(v string) predicate.User {
|
||||
return predicate.User(sql.FieldLT(FieldPasswordHash, v))
|
||||
}
|
||||
|
||||
// PasswordHashLTE applies the LTE predicate on the "password_hash" field.
|
||||
func PasswordHashLTE(v string) predicate.User {
|
||||
return predicate.User(sql.FieldLTE(FieldPasswordHash, v))
|
||||
}
|
||||
|
||||
// PasswordHashContains applies the Contains predicate on the "password_hash" field.
|
||||
func PasswordHashContains(v string) predicate.User {
|
||||
return predicate.User(sql.FieldContains(FieldPasswordHash, v))
|
||||
}
|
||||
|
||||
// PasswordHashHasPrefix applies the HasPrefix predicate on the "password_hash" field.
|
||||
func PasswordHashHasPrefix(v string) predicate.User {
|
||||
return predicate.User(sql.FieldHasPrefix(FieldPasswordHash, v))
|
||||
}
|
||||
|
||||
// PasswordHashHasSuffix applies the HasSuffix predicate on the "password_hash" field.
|
||||
func PasswordHashHasSuffix(v string) predicate.User {
|
||||
return predicate.User(sql.FieldHasSuffix(FieldPasswordHash, v))
|
||||
}
|
||||
|
||||
// PasswordHashEqualFold applies the EqualFold predicate on the "password_hash" field.
|
||||
func PasswordHashEqualFold(v string) predicate.User {
|
||||
return predicate.User(sql.FieldEqualFold(FieldPasswordHash, v))
|
||||
}
|
||||
|
||||
// PasswordHashContainsFold applies the ContainsFold predicate on the "password_hash" field.
|
||||
func PasswordHashContainsFold(v string) predicate.User {
|
||||
return predicate.User(sql.FieldContainsFold(FieldPasswordHash, v))
|
||||
}
|
||||
|
||||
// VerifiedEQ applies the EQ predicate on the "verified" field.
|
||||
func VerifiedEQ(v bool) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldVerified, v))
|
||||
}
|
||||
|
||||
// VerifiedNEQ applies the NEQ predicate on the "verified" field.
|
||||
func VerifiedNEQ(v bool) predicate.User {
|
||||
return predicate.User(sql.FieldNEQ(FieldVerified, v))
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
func CreatedAtEQ(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
|
||||
func CreatedAtNEQ(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldNEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtIn applies the In predicate on the "created_at" field.
|
||||
func CreatedAtIn(vs ...time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
|
||||
func CreatedAtNotIn(vs ...time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldNotIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtGT applies the GT predicate on the "created_at" field.
|
||||
func CreatedAtGT(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldGT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
|
||||
func CreatedAtGTE(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldGTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLT applies the LT predicate on the "created_at" field.
|
||||
func CreatedAtLT(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldLT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
|
||||
func CreatedAtLTE(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldLTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
|
||||
func UpdatedAtEQ(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
|
||||
func UpdatedAtNEQ(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldNEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtIn applies the In predicate on the "updated_at" field.
|
||||
func UpdatedAtIn(vs ...time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldIn(FieldUpdatedAt, vs...))
|
||||
}
|
||||
|
||||
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
|
||||
func UpdatedAtNotIn(vs ...time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldNotIn(FieldUpdatedAt, vs...))
|
||||
}
|
||||
|
||||
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
|
||||
func UpdatedAtGT(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldGT(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
|
||||
func UpdatedAtGTE(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldGTE(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
|
||||
func UpdatedAtLT(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldLT(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
|
||||
func UpdatedAtLTE(v time.Time) predicate.User {
|
||||
return predicate.User(sql.FieldLTE(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// HasUserRoles applies the HasEdge predicate on the "user_roles" edge.
|
||||
func HasUserRoles() predicate.User {
|
||||
return predicate.User(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, UserRolesTable, UserRolesColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasUserRolesWith applies the HasEdge predicate on the "user_roles" edge with a given conditions (other predicates).
|
||||
func HasUserRolesWith(preds ...predicate.UserRole) predicate.User {
|
||||
return predicate.User(func(s *sql.Selector) {
|
||||
step := newUserRolesStep()
|
||||
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
|
||||
for _, p := range preds {
|
||||
p(s)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// And groups predicates with the AND operator between them.
|
||||
func And(predicates ...predicate.User) predicate.User {
|
||||
return predicate.User(sql.AndPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.User) predicate.User {
|
||||
return predicate.User(sql.OrPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.User) predicate.User {
|
||||
return predicate.User(sql.NotPredicates(p))
|
||||
}
|
||||
331
internal/ent/user_create.go
Normal file
331
internal/ent/user_create.go
Normal file
@@ -0,0 +1,331 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/user"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/userrole"
|
||||
)
|
||||
|
||||
// UserCreate is the builder for creating a User entity.
|
||||
type UserCreate struct {
|
||||
config
|
||||
mutation *UserMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetEmail sets the "email" field.
|
||||
func (_c *UserCreate) SetEmail(v string) *UserCreate {
|
||||
_c.mutation.SetEmail(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetPasswordHash sets the "password_hash" field.
|
||||
func (_c *UserCreate) SetPasswordHash(v string) *UserCreate {
|
||||
_c.mutation.SetPasswordHash(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetVerified sets the "verified" field.
|
||||
func (_c *UserCreate) SetVerified(v bool) *UserCreate {
|
||||
_c.mutation.SetVerified(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableVerified sets the "verified" field if the given value is not nil.
|
||||
func (_c *UserCreate) SetNillableVerified(v *bool) *UserCreate {
|
||||
if v != nil {
|
||||
_c.SetVerified(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
func (_c *UserCreate) SetCreatedAt(v time.Time) *UserCreate {
|
||||
_c.mutation.SetCreatedAt(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
|
||||
func (_c *UserCreate) SetNillableCreatedAt(v *time.Time) *UserCreate {
|
||||
if v != nil {
|
||||
_c.SetCreatedAt(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (_c *UserCreate) SetUpdatedAt(v time.Time) *UserCreate {
|
||||
_c.mutation.SetUpdatedAt(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
|
||||
func (_c *UserCreate) SetNillableUpdatedAt(v *time.Time) *UserCreate {
|
||||
if v != nil {
|
||||
_c.SetUpdatedAt(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetID sets the "id" field.
|
||||
func (_c *UserCreate) SetID(v string) *UserCreate {
|
||||
_c.mutation.SetID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// AddUserRoleIDs adds the "user_roles" edge to the UserRole entity by IDs.
|
||||
func (_c *UserCreate) AddUserRoleIDs(ids ...int) *UserCreate {
|
||||
_c.mutation.AddUserRoleIDs(ids...)
|
||||
return _c
|
||||
}
|
||||
|
||||
// AddUserRoles adds the "user_roles" edges to the UserRole entity.
|
||||
func (_c *UserCreate) AddUserRoles(v ...*UserRole) *UserCreate {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _c.AddUserRoleIDs(ids...)
|
||||
}
|
||||
|
||||
// Mutation returns the UserMutation object of the builder.
|
||||
func (_c *UserCreate) Mutation() *UserMutation {
|
||||
return _c.mutation
|
||||
}
|
||||
|
||||
// Save creates the User in the database.
|
||||
func (_c *UserCreate) Save(ctx context.Context) (*User, error) {
|
||||
_c.defaults()
|
||||
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (_c *UserCreate) SaveX(ctx context.Context) *User {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *UserCreate) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *UserCreate) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaults sets the default values of the builder before save.
|
||||
func (_c *UserCreate) defaults() {
|
||||
if _, ok := _c.mutation.Verified(); !ok {
|
||||
v := user.DefaultVerified
|
||||
_c.mutation.SetVerified(v)
|
||||
}
|
||||
if _, ok := _c.mutation.CreatedAt(); !ok {
|
||||
v := user.DefaultCreatedAt()
|
||||
_c.mutation.SetCreatedAt(v)
|
||||
}
|
||||
if _, ok := _c.mutation.UpdatedAt(); !ok {
|
||||
v := user.DefaultUpdatedAt()
|
||||
_c.mutation.SetUpdatedAt(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_c *UserCreate) check() error {
|
||||
if _, ok := _c.mutation.Email(); !ok {
|
||||
return &ValidationError{Name: "email", err: errors.New(`ent: missing required field "User.email"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.Email(); ok {
|
||||
if err := user.EmailValidator(v); err != nil {
|
||||
return &ValidationError{Name: "email", err: fmt.Errorf(`ent: validator failed for field "User.email": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.PasswordHash(); !ok {
|
||||
return &ValidationError{Name: "password_hash", err: errors.New(`ent: missing required field "User.password_hash"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.PasswordHash(); ok {
|
||||
if err := user.PasswordHashValidator(v); err != nil {
|
||||
return &ValidationError{Name: "password_hash", err: fmt.Errorf(`ent: validator failed for field "User.password_hash": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.Verified(); !ok {
|
||||
return &ValidationError{Name: "verified", err: errors.New(`ent: missing required field "User.verified"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.CreatedAt(); !ok {
|
||||
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "User.created_at"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.UpdatedAt(); !ok {
|
||||
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "User.updated_at"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_c *UserCreate) sqlSave(ctx context.Context) (*User, error) {
|
||||
if err := _c.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := _c.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if _spec.ID.Value != nil {
|
||||
if id, ok := _spec.ID.Value.(string); ok {
|
||||
_node.ID = id
|
||||
} else {
|
||||
return nil, fmt.Errorf("unexpected User.ID type: %T", _spec.ID.Value)
|
||||
}
|
||||
}
|
||||
_c.mutation.id = &_node.ID
|
||||
_c.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &User{config: _c.config}
|
||||
_spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeString))
|
||||
)
|
||||
if id, ok := _c.mutation.ID(); ok {
|
||||
_node.ID = id
|
||||
_spec.ID.Value = id
|
||||
}
|
||||
if value, ok := _c.mutation.Email(); ok {
|
||||
_spec.SetField(user.FieldEmail, field.TypeString, value)
|
||||
_node.Email = value
|
||||
}
|
||||
if value, ok := _c.mutation.PasswordHash(); ok {
|
||||
_spec.SetField(user.FieldPasswordHash, field.TypeString, value)
|
||||
_node.PasswordHash = value
|
||||
}
|
||||
if value, ok := _c.mutation.Verified(); ok {
|
||||
_spec.SetField(user.FieldVerified, field.TypeBool, value)
|
||||
_node.Verified = value
|
||||
}
|
||||
if value, ok := _c.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(user.FieldCreatedAt, field.TypeTime, value)
|
||||
_node.CreatedAt = value
|
||||
}
|
||||
if value, ok := _c.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(user.FieldUpdatedAt, field.TypeTime, value)
|
||||
_node.UpdatedAt = value
|
||||
}
|
||||
if nodes := _c.mutation.UserRolesIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: user.UserRolesTable,
|
||||
Columns: []string{user.UserRolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// UserCreateBulk is the builder for creating many User entities in bulk.
|
||||
type UserCreateBulk struct {
|
||||
config
|
||||
err error
|
||||
builders []*UserCreate
|
||||
}
|
||||
|
||||
// Save creates the User entities in the database.
|
||||
func (_c *UserCreateBulk) Save(ctx context.Context) ([]*User, error) {
|
||||
if _c.err != nil {
|
||||
return nil, _c.err
|
||||
}
|
||||
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
|
||||
nodes := make([]*User, len(_c.builders))
|
||||
mutators := make([]Mutator, len(_c.builders))
|
||||
for i := range _c.builders {
|
||||
func(i int, root context.Context) {
|
||||
builder := _c.builders[i]
|
||||
builder.defaults()
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*UserMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err := builder.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
builder.mutation = mutation
|
||||
var err error
|
||||
nodes[i], specs[i] = builder.createSpec()
|
||||
if i < len(mutators)-1 {
|
||||
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
|
||||
} else {
|
||||
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
|
||||
// Invoke the actual operation on the latest mutation in the chain.
|
||||
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &nodes[i].ID
|
||||
mutation.done = true
|
||||
return nodes[i], nil
|
||||
})
|
||||
for i := len(builder.hooks) - 1; i >= 0; i-- {
|
||||
mut = builder.hooks[i](mut)
|
||||
}
|
||||
mutators[i] = mut
|
||||
}(i, ctx)
|
||||
}
|
||||
if len(mutators) > 0 {
|
||||
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_c *UserCreateBulk) SaveX(ctx context.Context) []*User {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *UserCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *UserCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
88
internal/ent/user_delete.go
Normal file
88
internal/ent/user_delete.go
Normal file
@@ -0,0 +1,88 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/user"
|
||||
)
|
||||
|
||||
// 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 (_d *UserDelete) Where(ps ...predicate.User) *UserDelete {
|
||||
_d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (_d *UserDelete) Exec(ctx context.Context) (int, error) {
|
||||
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *UserDelete) ExecX(ctx context.Context) int {
|
||||
n, err := _d.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (_d *UserDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeString))
|
||||
if ps := _d.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
|
||||
if err != nil && sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
_d.mutation.done = true
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// UserDeleteOne is the builder for deleting a single User entity.
|
||||
type UserDeleteOne struct {
|
||||
_d *UserDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the UserDelete builder.
|
||||
func (_d *UserDeleteOne) Where(ps ...predicate.User) *UserDeleteOne {
|
||||
_d._d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (_d *UserDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := _d._d.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 (_d *UserDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := _d.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
607
internal/ent/user_query.go
Normal file
607
internal/ent/user_query.go
Normal file
@@ -0,0 +1,607 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/user"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/userrole"
|
||||
)
|
||||
|
||||
// UserQuery is the builder for querying User entities.
|
||||
type UserQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []user.OrderOption
|
||||
inters []Interceptor
|
||||
predicates []predicate.User
|
||||
withUserRoles *UserRoleQuery
|
||||
// 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 (_q *UserQuery) Where(ps ...predicate.User) *UserQuery {
|
||||
_q.predicates = append(_q.predicates, ps...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
func (_q *UserQuery) Limit(limit int) *UserQuery {
|
||||
_q.ctx.Limit = &limit
|
||||
return _q
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
func (_q *UserQuery) Offset(offset int) *UserQuery {
|
||||
_q.ctx.Offset = &offset
|
||||
return _q
|
||||
}
|
||||
|
||||
// Unique configures the query builder to filter duplicate records on query.
|
||||
// By default, unique is set to true, and can be disabled using this method.
|
||||
func (_q *UserQuery) Unique(unique bool) *UserQuery {
|
||||
_q.ctx.Unique = &unique
|
||||
return _q
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
func (_q *UserQuery) Order(o ...user.OrderOption) *UserQuery {
|
||||
_q.order = append(_q.order, o...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// QueryUserRoles chains the current query on the "user_roles" edge.
|
||||
func (_q *UserQuery) QueryUserRoles() *UserRoleQuery {
|
||||
query := (&UserRoleClient{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(user.Table, user.FieldID, selector),
|
||||
sqlgraph.To(userrole.Table, userrole.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, user.UserRolesTable, user.UserRolesColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.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 (_q *UserQuery) First(ctx context.Context) (*User, error) {
|
||||
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nil, &NotFoundError{user.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (_q *UserQuery) FirstX(ctx context.Context) *User {
|
||||
node, err := _q.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 (_q *UserQuery) FirstID(ctx context.Context) (id string, err error) {
|
||||
var ids []string
|
||||
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); 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 (_q *UserQuery) FirstIDX(ctx context.Context) string {
|
||||
id, err := _q.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 (_q *UserQuery) Only(ctx context.Context) (*User, error) {
|
||||
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch len(nodes) {
|
||||
case 1:
|
||||
return nodes[0], nil
|
||||
case 0:
|
||||
return nil, &NotFoundError{user.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{user.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (_q *UserQuery) OnlyX(ctx context.Context) *User {
|
||||
node, err := _q.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 (_q *UserQuery) OnlyID(ctx context.Context) (id string, err error) {
|
||||
var ids []string
|
||||
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(ids) {
|
||||
case 1:
|
||||
id = ids[0]
|
||||
case 0:
|
||||
err = &NotFoundError{user.Label}
|
||||
default:
|
||||
err = &NotSingularError{user.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (_q *UserQuery) OnlyIDX(ctx context.Context) string {
|
||||
id, err := _q.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of Users.
|
||||
func (_q *UserQuery) All(ctx context.Context) ([]*User, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*User, *UserQuery]()
|
||||
return withInterceptors[[]*User](ctx, _q, qr, _q.inters)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (_q *UserQuery) AllX(ctx context.Context) []*User {
|
||||
nodes, err := _q.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of User IDs.
|
||||
func (_q *UserQuery) IDs(ctx context.Context) (ids []string, err error) {
|
||||
if _q.ctx.Unique == nil && _q.path != nil {
|
||||
_q.Unique(true)
|
||||
}
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
|
||||
if err = _q.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 (_q *UserQuery) IDsX(ctx context.Context) []string {
|
||||
ids, err := _q.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (_q *UserQuery) Count(ctx context.Context) (int, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return withInterceptors[int](ctx, _q, querierCount[*UserQuery](), _q.inters)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (_q *UserQuery) CountX(ctx context.Context) int {
|
||||
count, err := _q.Count(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// Exist returns true if the query has elements in the graph.
|
||||
func (_q *UserQuery) Exist(ctx context.Context) (bool, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
|
||||
switch _, err := _q.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExistX is like Exist, but panics if an error occurs.
|
||||
func (_q *UserQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := _q.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 (_q *UserQuery) Clone() *UserQuery {
|
||||
if _q == nil {
|
||||
return nil
|
||||
}
|
||||
return &UserQuery{
|
||||
config: _q.config,
|
||||
ctx: _q.ctx.Clone(),
|
||||
order: append([]user.OrderOption{}, _q.order...),
|
||||
inters: append([]Interceptor{}, _q.inters...),
|
||||
predicates: append([]predicate.User{}, _q.predicates...),
|
||||
withUserRoles: _q.withUserRoles.Clone(),
|
||||
// clone intermediate query.
|
||||
sql: _q.sql.Clone(),
|
||||
path: _q.path,
|
||||
}
|
||||
}
|
||||
|
||||
// WithUserRoles tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "user_roles" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *UserQuery) WithUserRoles(opts ...func(*UserRoleQuery)) *UserQuery {
|
||||
query := (&UserRoleClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withUserRoles = query
|
||||
return _q
|
||||
}
|
||||
|
||||
// GroupBy is used to group vertices by one or more fields/columns.
|
||||
// It is often used with aggregate functions, like: count, max, mean, min, sum.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// Email string `json:"email,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.User.Query().
|
||||
// GroupBy(user.FieldEmail).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy {
|
||||
_q.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &UserGroupBy{build: _q}
|
||||
grbuild.flds = &_q.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 {
|
||||
// Email string `json:"email,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.User.Query().
|
||||
// Select(user.FieldEmail).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *UserQuery) Select(fields ...string) *UserSelect {
|
||||
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
|
||||
sbuild := &UserSelect{UserQuery: _q}
|
||||
sbuild.label = user.Label
|
||||
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a UserSelect configured with the given aggregations.
|
||||
func (_q *UserQuery) Aggregate(fns ...AggregateFunc) *UserSelect {
|
||||
return _q.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (_q *UserQuery) prepareQuery(ctx context.Context) error {
|
||||
for _, inter := range _q.inters {
|
||||
if inter == nil {
|
||||
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
|
||||
}
|
||||
if trv, ok := inter.(Traverser); ok {
|
||||
if err := trv.Traverse(ctx, _q); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range _q.ctx.Fields {
|
||||
if !user.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
}
|
||||
if _q.path != nil {
|
||||
prev, err := _q.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_q.sql = prev
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) {
|
||||
var (
|
||||
nodes = []*User{}
|
||||
_spec = _q.querySpec()
|
||||
loadedTypes = [1]bool{
|
||||
_q.withUserRoles != nil,
|
||||
}
|
||||
)
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*User).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &User{config: _q.config}
|
||||
nodes = append(nodes, node)
|
||||
node.Edges.loadedTypes = loadedTypes
|
||||
return node.assignValues(columns, values)
|
||||
}
|
||||
for i := range hooks {
|
||||
hooks[i](ctx, _spec)
|
||||
}
|
||||
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nodes, nil
|
||||
}
|
||||
if query := _q.withUserRoles; query != nil {
|
||||
if err := _q.loadUserRoles(ctx, query, nodes,
|
||||
func(n *User) { n.Edges.UserRoles = []*UserRole{} },
|
||||
func(n *User, e *UserRole) { n.Edges.UserRoles = append(n.Edges.UserRoles, e) }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (_q *UserQuery) loadUserRoles(ctx context.Context, query *UserRoleQuery, nodes []*User, init func(*User), assign func(*User, *UserRole)) error {
|
||||
fks := make([]driver.Value, 0, len(nodes))
|
||||
nodeids := make(map[string]*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.UserRole(func(s *sql.Selector) {
|
||||
s.Where(sql.InValues(s.C(user.UserRolesColumn), fks...))
|
||||
}))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range neighbors {
|
||||
fk := n.user_user_roles
|
||||
if fk == nil {
|
||||
return fmt.Errorf(`foreign-key "user_user_roles" is nil for node %v`, n.ID)
|
||||
}
|
||||
node, ok := nodeids[*fk]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected referenced foreign-key "user_user_roles" returned %v for node %v`, *fk, n.ID)
|
||||
}
|
||||
assign(node, n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *UserQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := _q.querySpec()
|
||||
_spec.Node.Columns = _q.ctx.Fields
|
||||
if len(_q.ctx.Fields) > 0 {
|
||||
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
|
||||
}
|
||||
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
|
||||
}
|
||||
|
||||
func (_q *UserQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := sqlgraph.NewQuerySpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeString))
|
||||
_spec.From = _q.sql
|
||||
if unique := _q.ctx.Unique; unique != nil {
|
||||
_spec.Unique = *unique
|
||||
} else if _q.path != nil {
|
||||
_spec.Unique = true
|
||||
}
|
||||
if fields := _q.ctx.Fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, user.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != user.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := _q.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit := _q.ctx.Limit; limit != nil {
|
||||
_spec.Limit = *limit
|
||||
}
|
||||
if offset := _q.ctx.Offset; offset != nil {
|
||||
_spec.Offset = *offset
|
||||
}
|
||||
if ps := _q.order; len(ps) > 0 {
|
||||
_spec.Order = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
return _spec
|
||||
}
|
||||
|
||||
func (_q *UserQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(_q.driver.Dialect())
|
||||
t1 := builder.Table(user.Table)
|
||||
columns := _q.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = user.Columns
|
||||
}
|
||||
selector := builder.Select(t1.Columns(columns...)...).From(t1)
|
||||
if _q.sql != nil {
|
||||
selector = _q.sql
|
||||
selector.Select(selector.Columns(columns...)...)
|
||||
}
|
||||
if _q.ctx.Unique != nil && *_q.ctx.Unique {
|
||||
selector.Distinct()
|
||||
}
|
||||
for _, p := range _q.predicates {
|
||||
p(selector)
|
||||
}
|
||||
for _, p := range _q.order {
|
||||
p(selector)
|
||||
}
|
||||
if offset := _q.ctx.Offset; offset != nil {
|
||||
// limit is mandatory for offset clause. We start
|
||||
// with default value, and override it below if needed.
|
||||
selector.Offset(*offset).Limit(math.MaxInt32)
|
||||
}
|
||||
if limit := _q.ctx.Limit; limit != nil {
|
||||
selector.Limit(*limit)
|
||||
}
|
||||
return selector
|
||||
}
|
||||
|
||||
// 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 (_g *UserGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupBy {
|
||||
_g.fns = append(_g.fns, fns...)
|
||||
return _g
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_g *UserGroupBy) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
|
||||
if err := _g.build.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*UserQuery, *UserGroupBy](ctx, _g.build, _g, _g.build.inters, v)
|
||||
}
|
||||
|
||||
func (_g *UserGroupBy) sqlScan(ctx context.Context, root *UserQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx).Select()
|
||||
aggregation := make([]string, 0, len(_g.fns))
|
||||
for _, fn := range _g.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
|
||||
for _, f := range *_g.flds {
|
||||
columns = append(columns, selector.C(f))
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
selector.GroupBy(selector.Columns(*_g.flds...)...)
|
||||
if err := selector.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
// 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 (_s *UserSelect) Aggregate(fns ...AggregateFunc) *UserSelect {
|
||||
_s.fns = append(_s.fns, fns...)
|
||||
return _s
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_s *UserSelect) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
|
||||
if err := _s.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*UserQuery, *UserSelect](ctx, _s.UserQuery, _s, _s.inters, v)
|
||||
}
|
||||
|
||||
func (_s *UserSelect) sqlScan(ctx context.Context, root *UserQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx)
|
||||
aggregation := make([]string, 0, len(_s.fns))
|
||||
for _, fn := range _s.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
switch n := len(*_s.selector.flds); {
|
||||
case n == 0 && len(aggregation) > 0:
|
||||
selector.Select(aggregation...)
|
||||
case n != 0 && len(aggregation) > 0:
|
||||
selector.AppendSelect(aggregation...)
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
513
internal/ent/user_update.go
Normal file
513
internal/ent/user_update.go
Normal file
@@ -0,0 +1,513 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/user"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/userrole"
|
||||
)
|
||||
|
||||
// UserUpdate is the builder for updating User entities.
|
||||
type UserUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *UserMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the UserUpdate builder.
|
||||
func (_u *UserUpdate) Where(ps ...predicate.User) *UserUpdate {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetEmail sets the "email" field.
|
||||
func (_u *UserUpdate) SetEmail(v string) *UserUpdate {
|
||||
_u.mutation.SetEmail(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableEmail sets the "email" field if the given value is not nil.
|
||||
func (_u *UserUpdate) SetNillableEmail(v *string) *UserUpdate {
|
||||
if v != nil {
|
||||
_u.SetEmail(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetPasswordHash sets the "password_hash" field.
|
||||
func (_u *UserUpdate) SetPasswordHash(v string) *UserUpdate {
|
||||
_u.mutation.SetPasswordHash(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillablePasswordHash sets the "password_hash" field if the given value is not nil.
|
||||
func (_u *UserUpdate) SetNillablePasswordHash(v *string) *UserUpdate {
|
||||
if v != nil {
|
||||
_u.SetPasswordHash(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetVerified sets the "verified" field.
|
||||
func (_u *UserUpdate) SetVerified(v bool) *UserUpdate {
|
||||
_u.mutation.SetVerified(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableVerified sets the "verified" field if the given value is not nil.
|
||||
func (_u *UserUpdate) SetNillableVerified(v *bool) *UserUpdate {
|
||||
if v != nil {
|
||||
_u.SetVerified(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (_u *UserUpdate) SetUpdatedAt(v time.Time) *UserUpdate {
|
||||
_u.mutation.SetUpdatedAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddUserRoleIDs adds the "user_roles" edge to the UserRole entity by IDs.
|
||||
func (_u *UserUpdate) AddUserRoleIDs(ids ...int) *UserUpdate {
|
||||
_u.mutation.AddUserRoleIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddUserRoles adds the "user_roles" edges to the UserRole entity.
|
||||
func (_u *UserUpdate) AddUserRoles(v ...*UserRole) *UserUpdate {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddUserRoleIDs(ids...)
|
||||
}
|
||||
|
||||
// Mutation returns the UserMutation object of the builder.
|
||||
func (_u *UserUpdate) Mutation() *UserMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearUserRoles clears all "user_roles" edges to the UserRole entity.
|
||||
func (_u *UserUpdate) ClearUserRoles() *UserUpdate {
|
||||
_u.mutation.ClearUserRoles()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveUserRoleIDs removes the "user_roles" edge to UserRole entities by IDs.
|
||||
func (_u *UserUpdate) RemoveUserRoleIDs(ids ...int) *UserUpdate {
|
||||
_u.mutation.RemoveUserRoleIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveUserRoles removes "user_roles" edges to UserRole entities.
|
||||
func (_u *UserUpdate) RemoveUserRoles(v ...*UserRole) *UserUpdate {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveUserRoleIDs(ids...)
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (_u *UserUpdate) Save(ctx context.Context) (int, error) {
|
||||
_u.defaults()
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *UserUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_u *UserUpdate) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *UserUpdate) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaults sets the default values of the builder before save.
|
||||
func (_u *UserUpdate) defaults() {
|
||||
if _, ok := _u.mutation.UpdatedAt(); !ok {
|
||||
v := user.UpdateDefaultUpdatedAt()
|
||||
_u.mutation.SetUpdatedAt(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *UserUpdate) check() error {
|
||||
if v, ok := _u.mutation.Email(); ok {
|
||||
if err := user.EmailValidator(v); err != nil {
|
||||
return &ValidationError{Name: "email", err: fmt.Errorf(`ent: validator failed for field "User.email": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.PasswordHash(); ok {
|
||||
if err := user.PasswordHashValidator(v); err != nil {
|
||||
return &ValidationError{Name: "password_hash", err: fmt.Errorf(`ent: validator failed for field "User.password_hash": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeString))
|
||||
if ps := _u.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := _u.mutation.Email(); ok {
|
||||
_spec.SetField(user.FieldEmail, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.PasswordHash(); ok {
|
||||
_spec.SetField(user.FieldPasswordHash, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Verified(); ok {
|
||||
_spec.SetField(user.FieldVerified, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := _u.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(user.FieldUpdatedAt, field.TypeTime, value)
|
||||
}
|
||||
if _u.mutation.UserRolesCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: user.UserRolesTable,
|
||||
Columns: []string{user.UserRolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedUserRolesIDs(); len(nodes) > 0 && !_u.mutation.UserRolesCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: user.UserRolesTable,
|
||||
Columns: []string{user.UserRolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(userrole.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 := _u.mutation.UserRolesIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: user.UserRolesTable,
|
||||
Columns: []string{user.UserRolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{user.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
// UserUpdateOne is the builder for updating a single User entity.
|
||||
type UserUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *UserMutation
|
||||
}
|
||||
|
||||
// SetEmail sets the "email" field.
|
||||
func (_u *UserUpdateOne) SetEmail(v string) *UserUpdateOne {
|
||||
_u.mutation.SetEmail(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableEmail sets the "email" field if the given value is not nil.
|
||||
func (_u *UserUpdateOne) SetNillableEmail(v *string) *UserUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetEmail(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetPasswordHash sets the "password_hash" field.
|
||||
func (_u *UserUpdateOne) SetPasswordHash(v string) *UserUpdateOne {
|
||||
_u.mutation.SetPasswordHash(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillablePasswordHash sets the "password_hash" field if the given value is not nil.
|
||||
func (_u *UserUpdateOne) SetNillablePasswordHash(v *string) *UserUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetPasswordHash(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetVerified sets the "verified" field.
|
||||
func (_u *UserUpdateOne) SetVerified(v bool) *UserUpdateOne {
|
||||
_u.mutation.SetVerified(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableVerified sets the "verified" field if the given value is not nil.
|
||||
func (_u *UserUpdateOne) SetNillableVerified(v *bool) *UserUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetVerified(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (_u *UserUpdateOne) SetUpdatedAt(v time.Time) *UserUpdateOne {
|
||||
_u.mutation.SetUpdatedAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddUserRoleIDs adds the "user_roles" edge to the UserRole entity by IDs.
|
||||
func (_u *UserUpdateOne) AddUserRoleIDs(ids ...int) *UserUpdateOne {
|
||||
_u.mutation.AddUserRoleIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddUserRoles adds the "user_roles" edges to the UserRole entity.
|
||||
func (_u *UserUpdateOne) AddUserRoles(v ...*UserRole) *UserUpdateOne {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddUserRoleIDs(ids...)
|
||||
}
|
||||
|
||||
// Mutation returns the UserMutation object of the builder.
|
||||
func (_u *UserUpdateOne) Mutation() *UserMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearUserRoles clears all "user_roles" edges to the UserRole entity.
|
||||
func (_u *UserUpdateOne) ClearUserRoles() *UserUpdateOne {
|
||||
_u.mutation.ClearUserRoles()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveUserRoleIDs removes the "user_roles" edge to UserRole entities by IDs.
|
||||
func (_u *UserUpdateOne) RemoveUserRoleIDs(ids ...int) *UserUpdateOne {
|
||||
_u.mutation.RemoveUserRoleIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveUserRoles removes "user_roles" edges to UserRole entities.
|
||||
func (_u *UserUpdateOne) RemoveUserRoles(v ...*UserRole) *UserUpdateOne {
|
||||
ids := make([]int, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveUserRoleIDs(ids...)
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the UserUpdate builder.
|
||||
func (_u *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Select allows selecting one or more fields (columns) of the returned entity.
|
||||
// The default is selecting all fields defined in the entity schema.
|
||||
func (_u *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne {
|
||||
_u.fields = append([]string{field}, fields...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated User entity.
|
||||
func (_u *UserUpdateOne) Save(ctx context.Context) (*User, error) {
|
||||
_u.defaults()
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *UserUpdateOne) SaveX(ctx context.Context) *User {
|
||||
node, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (_u *UserUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *UserUpdateOne) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// defaults sets the default values of the builder before save.
|
||||
func (_u *UserUpdateOne) defaults() {
|
||||
if _, ok := _u.mutation.UpdatedAt(); !ok {
|
||||
v := user.UpdateDefaultUpdatedAt()
|
||||
_u.mutation.SetUpdatedAt(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *UserUpdateOne) check() error {
|
||||
if v, ok := _u.mutation.Email(); ok {
|
||||
if err := user.EmailValidator(v); err != nil {
|
||||
return &ValidationError{Name: "email", err: fmt.Errorf(`ent: validator failed for field "User.email": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.PasswordHash(); ok {
|
||||
if err := user.PasswordHashValidator(v); err != nil {
|
||||
return &ValidationError{Name: "password_hash", err: fmt.Errorf(`ent: validator failed for field "User.password_hash": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeString))
|
||||
id, ok := _u.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "User.id" for update`)}
|
||||
}
|
||||
_spec.Node.ID.Value = id
|
||||
if fields := _u.fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, user.FieldID)
|
||||
for _, f := range fields {
|
||||
if !user.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != user.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := _u.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value, ok := _u.mutation.Email(); ok {
|
||||
_spec.SetField(user.FieldEmail, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.PasswordHash(); ok {
|
||||
_spec.SetField(user.FieldPasswordHash, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Verified(); ok {
|
||||
_spec.SetField(user.FieldVerified, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := _u.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(user.FieldUpdatedAt, field.TypeTime, value)
|
||||
}
|
||||
if _u.mutation.UserRolesCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: user.UserRolesTable,
|
||||
Columns: []string{user.UserRolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedUserRolesIDs(); len(nodes) > 0 && !_u.mutation.UserRolesCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: user.UserRolesTable,
|
||||
Columns: []string{user.UserRolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(userrole.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 := _u.mutation.UserRolesIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: user.UserRolesTable,
|
||||
Columns: []string{user.UserRolesColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
_node = &User{config: _u.config}
|
||||
_spec.Assign = _node.assignValues
|
||||
_spec.ScanValues = _node.scanValues
|
||||
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{user.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
182
internal/ent/userrole.go
Normal file
182
internal/ent/userrole.go
Normal file
@@ -0,0 +1,182 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/user"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/userrole"
|
||||
)
|
||||
|
||||
// UserRole is the model entity for the UserRole schema.
|
||||
type UserRole struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID int `json:"id,omitempty"`
|
||||
// UserID holds the value of the "user_id" field.
|
||||
UserID string `json:"user_id,omitempty"`
|
||||
// RoleID holds the value of the "role_id" field.
|
||||
RoleID string `json:"role_id,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
// The values are being populated by the UserRoleQuery when eager-loading is set.
|
||||
Edges UserRoleEdges `json:"edges"`
|
||||
role_user_roles *string
|
||||
user_user_roles *string
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// UserRoleEdges holds the relations/edges for other nodes in the graph.
|
||||
type UserRoleEdges struct {
|
||||
// User holds the value of the user edge.
|
||||
User *User `json:"user,omitempty"`
|
||||
// Role holds the value of the role edge.
|
||||
Role *Role `json:"role,omitempty"`
|
||||
// loadedTypes holds the information for reporting if a
|
||||
// type was loaded (or requested) in eager-loading or not.
|
||||
loadedTypes [2]bool
|
||||
}
|
||||
|
||||
// UserOrErr returns the User value or an error if the edge
|
||||
// was not loaded in eager-loading, or loaded but was not found.
|
||||
func (e UserRoleEdges) UserOrErr() (*User, error) {
|
||||
if e.User != nil {
|
||||
return e.User, nil
|
||||
} else if e.loadedTypes[0] {
|
||||
return nil, &NotFoundError{label: user.Label}
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "user"}
|
||||
}
|
||||
|
||||
// RoleOrErr returns the Role value or an error if the edge
|
||||
// was not loaded in eager-loading, or loaded but was not found.
|
||||
func (e UserRoleEdges) RoleOrErr() (*Role, error) {
|
||||
if e.Role != nil {
|
||||
return e.Role, nil
|
||||
} else if e.loadedTypes[1] {
|
||||
return nil, &NotFoundError{label: role.Label}
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "role"}
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*UserRole) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case userrole.FieldID:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case userrole.FieldUserID, userrole.FieldRoleID:
|
||||
values[i] = new(sql.NullString)
|
||||
case userrole.ForeignKeys[0]: // role_user_roles
|
||||
values[i] = new(sql.NullString)
|
||||
case userrole.ForeignKeys[1]: // user_user_roles
|
||||
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 UserRole fields.
|
||||
func (_m *UserRole) 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 userrole.FieldID:
|
||||
value, ok := values[i].(*sql.NullInt64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", value)
|
||||
}
|
||||
_m.ID = int(value.Int64)
|
||||
case userrole.FieldUserID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field user_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.UserID = value.String
|
||||
}
|
||||
case userrole.FieldRoleID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field role_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.RoleID = value.String
|
||||
}
|
||||
case userrole.ForeignKeys[0]:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field role_user_roles", values[i])
|
||||
} else if value.Valid {
|
||||
_m.role_user_roles = new(string)
|
||||
*_m.role_user_roles = value.String
|
||||
}
|
||||
case userrole.ForeignKeys[1]:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field user_user_roles", values[i])
|
||||
} else if value.Valid {
|
||||
_m.user_user_roles = new(string)
|
||||
*_m.user_user_roles = value.String
|
||||
}
|
||||
default:
|
||||
_m.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value returns the ent.Value that was dynamically selected and assigned to the UserRole.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (_m *UserRole) Value(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// QueryUser queries the "user" edge of the UserRole entity.
|
||||
func (_m *UserRole) QueryUser() *UserQuery {
|
||||
return NewUserRoleClient(_m.config).QueryUser(_m)
|
||||
}
|
||||
|
||||
// QueryRole queries the "role" edge of the UserRole entity.
|
||||
func (_m *UserRole) QueryRole() *RoleQuery {
|
||||
return NewUserRoleClient(_m.config).QueryRole(_m)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this UserRole.
|
||||
// Note that you need to call UserRole.Unwrap() before calling this method if this UserRole
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (_m *UserRole) Update() *UserRoleUpdateOne {
|
||||
return NewUserRoleClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the UserRole entity that was returned from a transaction after it was closed,
|
||||
// so that all future queries will be executed through the driver which created the transaction.
|
||||
func (_m *UserRole) Unwrap() *UserRole {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: UserRole is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *UserRole) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("UserRole(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
builder.WriteString("user_id=")
|
||||
builder.WriteString(_m.UserID)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("role_id=")
|
||||
builder.WriteString(_m.RoleID)
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// UserRoles is a parsable slice of UserRole.
|
||||
type UserRoles []*UserRole
|
||||
114
internal/ent/userrole/userrole.go
Normal file
114
internal/ent/userrole/userrole.go
Normal file
@@ -0,0 +1,114 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package userrole
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the userrole type in the database.
|
||||
Label = "user_role"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldUserID holds the string denoting the user_id field in the database.
|
||||
FieldUserID = "user_id"
|
||||
// FieldRoleID holds the string denoting the role_id field in the database.
|
||||
FieldRoleID = "role_id"
|
||||
// EdgeUser holds the string denoting the user edge name in mutations.
|
||||
EdgeUser = "user"
|
||||
// EdgeRole holds the string denoting the role edge name in mutations.
|
||||
EdgeRole = "role"
|
||||
// Table holds the table name of the userrole in the database.
|
||||
Table = "user_roles"
|
||||
// UserTable is the table that holds the user relation/edge.
|
||||
UserTable = "user_roles"
|
||||
// UserInverseTable is the table name for the User entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "user" package.
|
||||
UserInverseTable = "users"
|
||||
// UserColumn is the table column denoting the user relation/edge.
|
||||
UserColumn = "user_id"
|
||||
// RoleTable is the table that holds the role relation/edge.
|
||||
RoleTable = "user_roles"
|
||||
// RoleInverseTable is the table name for the Role entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "role" package.
|
||||
RoleInverseTable = "roles"
|
||||
// RoleColumn is the table column denoting the role relation/edge.
|
||||
RoleColumn = "role_id"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for userrole fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldUserID,
|
||||
FieldRoleID,
|
||||
}
|
||||
|
||||
// ForeignKeys holds the SQL foreign-keys that are owned by the "user_roles"
|
||||
// table and are not defined as standalone fields in the schema.
|
||||
var ForeignKeys = []string{
|
||||
"role_user_roles",
|
||||
"user_user_roles",
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// OrderOption defines the ordering options for the UserRole 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()
|
||||
}
|
||||
|
||||
// ByUserID orders the results by the user_id field.
|
||||
func ByUserID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldUserID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByRoleID orders the results by the role_id field.
|
||||
func ByRoleID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldRoleID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByUserField orders the results by user field.
|
||||
func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...))
|
||||
}
|
||||
}
|
||||
|
||||
// ByRoleField orders the results by role field.
|
||||
func ByRoleField(field string, opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newRoleStep(), sql.OrderByField(field, opts...))
|
||||
}
|
||||
}
|
||||
func newUserStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(UserInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn),
|
||||
)
|
||||
}
|
||||
func newRoleStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(RoleInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, false, RoleTable, RoleColumn),
|
||||
)
|
||||
}
|
||||
255
internal/ent/userrole/where.go
Normal file
255
internal/ent/userrole/where.go
Normal file
@@ -0,0 +1,255 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package userrole
|
||||
|
||||
import (
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id int) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id int) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id int) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...int) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...int) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id int) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id int) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id int) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id int) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
|
||||
func UserID(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldEQ(FieldUserID, v))
|
||||
}
|
||||
|
||||
// RoleID applies equality check predicate on the "role_id" field. It's identical to RoleIDEQ.
|
||||
func RoleID(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldEQ(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// UserIDEQ applies the EQ predicate on the "user_id" field.
|
||||
func UserIDEQ(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldEQ(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDNEQ applies the NEQ predicate on the "user_id" field.
|
||||
func UserIDNEQ(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldNEQ(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDIn applies the In predicate on the "user_id" field.
|
||||
func UserIDIn(vs ...string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldIn(FieldUserID, vs...))
|
||||
}
|
||||
|
||||
// UserIDNotIn applies the NotIn predicate on the "user_id" field.
|
||||
func UserIDNotIn(vs ...string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldNotIn(FieldUserID, vs...))
|
||||
}
|
||||
|
||||
// UserIDGT applies the GT predicate on the "user_id" field.
|
||||
func UserIDGT(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldGT(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDGTE applies the GTE predicate on the "user_id" field.
|
||||
func UserIDGTE(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldGTE(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDLT applies the LT predicate on the "user_id" field.
|
||||
func UserIDLT(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldLT(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDLTE applies the LTE predicate on the "user_id" field.
|
||||
func UserIDLTE(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldLTE(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDContains applies the Contains predicate on the "user_id" field.
|
||||
func UserIDContains(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldContains(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDHasPrefix applies the HasPrefix predicate on the "user_id" field.
|
||||
func UserIDHasPrefix(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldHasPrefix(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDHasSuffix applies the HasSuffix predicate on the "user_id" field.
|
||||
func UserIDHasSuffix(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldHasSuffix(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDEqualFold applies the EqualFold predicate on the "user_id" field.
|
||||
func UserIDEqualFold(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldEqualFold(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDContainsFold applies the ContainsFold predicate on the "user_id" field.
|
||||
func UserIDContainsFold(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldContainsFold(FieldUserID, v))
|
||||
}
|
||||
|
||||
// RoleIDEQ applies the EQ predicate on the "role_id" field.
|
||||
func RoleIDEQ(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldEQ(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDNEQ applies the NEQ predicate on the "role_id" field.
|
||||
func RoleIDNEQ(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldNEQ(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDIn applies the In predicate on the "role_id" field.
|
||||
func RoleIDIn(vs ...string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldIn(FieldRoleID, vs...))
|
||||
}
|
||||
|
||||
// RoleIDNotIn applies the NotIn predicate on the "role_id" field.
|
||||
func RoleIDNotIn(vs ...string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldNotIn(FieldRoleID, vs...))
|
||||
}
|
||||
|
||||
// RoleIDGT applies the GT predicate on the "role_id" field.
|
||||
func RoleIDGT(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldGT(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDGTE applies the GTE predicate on the "role_id" field.
|
||||
func RoleIDGTE(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldGTE(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDLT applies the LT predicate on the "role_id" field.
|
||||
func RoleIDLT(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldLT(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDLTE applies the LTE predicate on the "role_id" field.
|
||||
func RoleIDLTE(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldLTE(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDContains applies the Contains predicate on the "role_id" field.
|
||||
func RoleIDContains(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldContains(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDHasPrefix applies the HasPrefix predicate on the "role_id" field.
|
||||
func RoleIDHasPrefix(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldHasPrefix(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDHasSuffix applies the HasSuffix predicate on the "role_id" field.
|
||||
func RoleIDHasSuffix(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldHasSuffix(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDEqualFold applies the EqualFold predicate on the "role_id" field.
|
||||
func RoleIDEqualFold(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldEqualFold(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// RoleIDContainsFold applies the ContainsFold predicate on the "role_id" field.
|
||||
func RoleIDContainsFold(v string) predicate.UserRole {
|
||||
return predicate.UserRole(sql.FieldContainsFold(FieldRoleID, v))
|
||||
}
|
||||
|
||||
// HasUser applies the HasEdge predicate on the "user" edge.
|
||||
func HasUser() predicate.UserRole {
|
||||
return predicate.UserRole(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates).
|
||||
func HasUserWith(preds ...predicate.User) predicate.UserRole {
|
||||
return predicate.UserRole(func(s *sql.Selector) {
|
||||
step := newUserStep()
|
||||
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
|
||||
for _, p := range preds {
|
||||
p(s)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// HasRole applies the HasEdge predicate on the "role" edge.
|
||||
func HasRole() predicate.UserRole {
|
||||
return predicate.UserRole(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, false, RoleTable, RoleColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasRoleWith applies the HasEdge predicate on the "role" edge with a given conditions (other predicates).
|
||||
func HasRoleWith(preds ...predicate.Role) predicate.UserRole {
|
||||
return predicate.UserRole(func(s *sql.Selector) {
|
||||
step := newRoleStep()
|
||||
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.UserRole) predicate.UserRole {
|
||||
return predicate.UserRole(sql.AndPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.UserRole) predicate.UserRole {
|
||||
return predicate.UserRole(sql.OrPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.UserRole) predicate.UserRole {
|
||||
return predicate.UserRole(sql.NotPredicates(p))
|
||||
}
|
||||
240
internal/ent/userrole_create.go
Normal file
240
internal/ent/userrole_create.go
Normal file
@@ -0,0 +1,240 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/user"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/userrole"
|
||||
)
|
||||
|
||||
// UserRoleCreate is the builder for creating a UserRole entity.
|
||||
type UserRoleCreate struct {
|
||||
config
|
||||
mutation *UserRoleMutation
|
||||
hooks []Hook
|
||||
}
|
||||
|
||||
// SetUserID sets the "user_id" field.
|
||||
func (_c *UserRoleCreate) SetUserID(v string) *UserRoleCreate {
|
||||
_c.mutation.SetUserID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetRoleID sets the "role_id" field.
|
||||
func (_c *UserRoleCreate) SetRoleID(v string) *UserRoleCreate {
|
||||
_c.mutation.SetRoleID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetUser sets the "user" edge to the User entity.
|
||||
func (_c *UserRoleCreate) SetUser(v *User) *UserRoleCreate {
|
||||
return _c.SetUserID(v.ID)
|
||||
}
|
||||
|
||||
// SetRole sets the "role" edge to the Role entity.
|
||||
func (_c *UserRoleCreate) SetRole(v *Role) *UserRoleCreate {
|
||||
return _c.SetRoleID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the UserRoleMutation object of the builder.
|
||||
func (_c *UserRoleCreate) Mutation() *UserRoleMutation {
|
||||
return _c.mutation
|
||||
}
|
||||
|
||||
// Save creates the UserRole in the database.
|
||||
func (_c *UserRoleCreate) Save(ctx context.Context) (*UserRole, error) {
|
||||
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (_c *UserRoleCreate) SaveX(ctx context.Context) *UserRole {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *UserRoleCreate) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *UserRoleCreate) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_c *UserRoleCreate) check() error {
|
||||
if _, ok := _c.mutation.UserID(); !ok {
|
||||
return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "UserRole.user_id"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.RoleID(); !ok {
|
||||
return &ValidationError{Name: "role_id", err: errors.New(`ent: missing required field "UserRole.role_id"`)}
|
||||
}
|
||||
if len(_c.mutation.UserIDs()) == 0 {
|
||||
return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "UserRole.user"`)}
|
||||
}
|
||||
if len(_c.mutation.RoleIDs()) == 0 {
|
||||
return &ValidationError{Name: "role", err: errors.New(`ent: missing required edge "UserRole.role"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_c *UserRoleCreate) sqlSave(ctx context.Context) (*UserRole, error) {
|
||||
if err := _c.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_node, _spec := _c.createSpec()
|
||||
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
id := _spec.ID.Value.(int64)
|
||||
_node.ID = int(id)
|
||||
_c.mutation.id = &_node.ID
|
||||
_c.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (_c *UserRoleCreate) createSpec() (*UserRole, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &UserRole{config: _c.config}
|
||||
_spec = sqlgraph.NewCreateSpec(userrole.Table, sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt))
|
||||
)
|
||||
if nodes := _c.mutation.UserIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: userrole.UserTable,
|
||||
Columns: []string{userrole.UserColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_node.UserID = nodes[0]
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
if nodes := _c.mutation.RoleIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: userrole.RoleTable,
|
||||
Columns: []string{userrole.RoleColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_node.RoleID = nodes[0]
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// UserRoleCreateBulk is the builder for creating many UserRole entities in bulk.
|
||||
type UserRoleCreateBulk struct {
|
||||
config
|
||||
err error
|
||||
builders []*UserRoleCreate
|
||||
}
|
||||
|
||||
// Save creates the UserRole entities in the database.
|
||||
func (_c *UserRoleCreateBulk) Save(ctx context.Context) ([]*UserRole, error) {
|
||||
if _c.err != nil {
|
||||
return nil, _c.err
|
||||
}
|
||||
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
|
||||
nodes := make([]*UserRole, len(_c.builders))
|
||||
mutators := make([]Mutator, len(_c.builders))
|
||||
for i := range _c.builders {
|
||||
func(i int, root context.Context) {
|
||||
builder := _c.builders[i]
|
||||
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
|
||||
mutation, ok := m.(*UserRoleMutation)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unexpected mutation type %T", m)
|
||||
}
|
||||
if err := builder.check(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
builder.mutation = mutation
|
||||
var err error
|
||||
nodes[i], specs[i] = builder.createSpec()
|
||||
if i < len(mutators)-1 {
|
||||
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
|
||||
} else {
|
||||
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
|
||||
// Invoke the actual operation on the latest mutation in the chain.
|
||||
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
|
||||
if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mutation.id = &nodes[i].ID
|
||||
if specs[i].ID.Value != nil {
|
||||
id := specs[i].ID.Value.(int64)
|
||||
nodes[i].ID = int(id)
|
||||
}
|
||||
mutation.done = true
|
||||
return nodes[i], nil
|
||||
})
|
||||
for i := len(builder.hooks) - 1; i >= 0; i-- {
|
||||
mut = builder.hooks[i](mut)
|
||||
}
|
||||
mutators[i] = mut
|
||||
}(i, ctx)
|
||||
}
|
||||
if len(mutators) > 0 {
|
||||
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_c *UserRoleCreateBulk) SaveX(ctx context.Context) []*UserRole {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *UserRoleCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *UserRoleCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
88
internal/ent/userrole_delete.go
Normal file
88
internal/ent/userrole_delete.go
Normal file
@@ -0,0 +1,88 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/userrole"
|
||||
)
|
||||
|
||||
// UserRoleDelete is the builder for deleting a UserRole entity.
|
||||
type UserRoleDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *UserRoleMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the UserRoleDelete builder.
|
||||
func (_d *UserRoleDelete) Where(ps ...predicate.UserRole) *UserRoleDelete {
|
||||
_d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (_d *UserRoleDelete) Exec(ctx context.Context) (int, error) {
|
||||
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *UserRoleDelete) ExecX(ctx context.Context) int {
|
||||
n, err := _d.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (_d *UserRoleDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(userrole.Table, sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt))
|
||||
if ps := _d.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
|
||||
if err != nil && sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
_d.mutation.done = true
|
||||
return affected, err
|
||||
}
|
||||
|
||||
// UserRoleDeleteOne is the builder for deleting a single UserRole entity.
|
||||
type UserRoleDeleteOne struct {
|
||||
_d *UserRoleDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the UserRoleDelete builder.
|
||||
func (_d *UserRoleDeleteOne) Where(ps ...predicate.UserRole) *UserRoleDeleteOne {
|
||||
_d._d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (_d *UserRoleDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := _d._d.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{userrole.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *UserRoleDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := _d.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
686
internal/ent/userrole_query.go
Normal file
686
internal/ent/userrole_query.go
Normal file
@@ -0,0 +1,686 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/user"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/userrole"
|
||||
)
|
||||
|
||||
// UserRoleQuery is the builder for querying UserRole entities.
|
||||
type UserRoleQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []userrole.OrderOption
|
||||
inters []Interceptor
|
||||
predicates []predicate.UserRole
|
||||
withUser *UserQuery
|
||||
withRole *RoleQuery
|
||||
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 UserRoleQuery builder.
|
||||
func (_q *UserRoleQuery) Where(ps ...predicate.UserRole) *UserRoleQuery {
|
||||
_q.predicates = append(_q.predicates, ps...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
func (_q *UserRoleQuery) Limit(limit int) *UserRoleQuery {
|
||||
_q.ctx.Limit = &limit
|
||||
return _q
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
func (_q *UserRoleQuery) Offset(offset int) *UserRoleQuery {
|
||||
_q.ctx.Offset = &offset
|
||||
return _q
|
||||
}
|
||||
|
||||
// Unique configures the query builder to filter duplicate records on query.
|
||||
// By default, unique is set to true, and can be disabled using this method.
|
||||
func (_q *UserRoleQuery) Unique(unique bool) *UserRoleQuery {
|
||||
_q.ctx.Unique = &unique
|
||||
return _q
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
func (_q *UserRoleQuery) Order(o ...userrole.OrderOption) *UserRoleQuery {
|
||||
_q.order = append(_q.order, o...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// QueryUser chains the current query on the "user" edge.
|
||||
func (_q *UserRoleQuery) QueryUser() *UserQuery {
|
||||
query := (&UserClient{config: _q.config}).Query()
|
||||
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
selector := _q.sqlQuery(ctx)
|
||||
if err := selector.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(userrole.Table, userrole.FieldID, selector),
|
||||
sqlgraph.To(user.Table, user.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, false, userrole.UserTable, userrole.UserColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// QueryRole chains the current query on the "role" edge.
|
||||
func (_q *UserRoleQuery) QueryRole() *RoleQuery {
|
||||
query := (&RoleClient{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(userrole.Table, userrole.FieldID, selector),
|
||||
sqlgraph.To(role.Table, role.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, false, userrole.RoleTable, userrole.RoleColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// First returns the first UserRole entity from the query.
|
||||
// Returns a *NotFoundError when no UserRole was found.
|
||||
func (_q *UserRoleQuery) First(ctx context.Context) (*UserRole, error) {
|
||||
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nil, &NotFoundError{userrole.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (_q *UserRoleQuery) FirstX(ctx context.Context) *UserRole {
|
||||
node, err := _q.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first UserRole ID from the query.
|
||||
// Returns a *NotFoundError when no UserRole ID was found.
|
||||
func (_q *UserRoleQuery) FirstID(ctx context.Context) (id int, err error) {
|
||||
var ids []int
|
||||
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &NotFoundError{userrole.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (_q *UserRoleQuery) FirstIDX(ctx context.Context) int {
|
||||
id, err := _q.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single UserRole entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when more than one UserRole entity is found.
|
||||
// Returns a *NotFoundError when no UserRole entities are found.
|
||||
func (_q *UserRoleQuery) Only(ctx context.Context) (*UserRole, error) {
|
||||
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch len(nodes) {
|
||||
case 1:
|
||||
return nodes[0], nil
|
||||
case 0:
|
||||
return nil, &NotFoundError{userrole.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{userrole.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (_q *UserRoleQuery) OnlyX(ctx context.Context) *UserRole {
|
||||
node, err := _q.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only UserRole ID in the query.
|
||||
// Returns a *NotSingularError when more than one UserRole ID is found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (_q *UserRoleQuery) OnlyID(ctx context.Context) (id int, err error) {
|
||||
var ids []int
|
||||
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
|
||||
return
|
||||
}
|
||||
switch len(ids) {
|
||||
case 1:
|
||||
id = ids[0]
|
||||
case 0:
|
||||
err = &NotFoundError{userrole.Label}
|
||||
default:
|
||||
err = &NotSingularError{userrole.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (_q *UserRoleQuery) OnlyIDX(ctx context.Context) int {
|
||||
id, err := _q.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of UserRoles.
|
||||
func (_q *UserRoleQuery) All(ctx context.Context) ([]*UserRole, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*UserRole, *UserRoleQuery]()
|
||||
return withInterceptors[[]*UserRole](ctx, _q, qr, _q.inters)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (_q *UserRoleQuery) AllX(ctx context.Context) []*UserRole {
|
||||
nodes, err := _q.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of UserRole IDs.
|
||||
func (_q *UserRoleQuery) IDs(ctx context.Context) (ids []int, err error) {
|
||||
if _q.ctx.Unique == nil && _q.path != nil {
|
||||
_q.Unique(true)
|
||||
}
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
|
||||
if err = _q.Select(userrole.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (_q *UserRoleQuery) IDsX(ctx context.Context) []int {
|
||||
ids, err := _q.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (_q *UserRoleQuery) Count(ctx context.Context) (int, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return withInterceptors[int](ctx, _q, querierCount[*UserRoleQuery](), _q.inters)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (_q *UserRoleQuery) CountX(ctx context.Context) int {
|
||||
count, err := _q.Count(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// Exist returns true if the query has elements in the graph.
|
||||
func (_q *UserRoleQuery) Exist(ctx context.Context) (bool, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
|
||||
switch _, err := _q.FirstID(ctx); {
|
||||
case IsNotFound(err):
|
||||
return false, nil
|
||||
case err != nil:
|
||||
return false, fmt.Errorf("ent: check existence: %w", err)
|
||||
default:
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExistX is like Exist, but panics if an error occurs.
|
||||
func (_q *UserRoleQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := _q.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the UserRoleQuery builder, including all associated steps. It can be
|
||||
// used to prepare common query builders and use them differently after the clone is made.
|
||||
func (_q *UserRoleQuery) Clone() *UserRoleQuery {
|
||||
if _q == nil {
|
||||
return nil
|
||||
}
|
||||
return &UserRoleQuery{
|
||||
config: _q.config,
|
||||
ctx: _q.ctx.Clone(),
|
||||
order: append([]userrole.OrderOption{}, _q.order...),
|
||||
inters: append([]Interceptor{}, _q.inters...),
|
||||
predicates: append([]predicate.UserRole{}, _q.predicates...),
|
||||
withUser: _q.withUser.Clone(),
|
||||
withRole: _q.withRole.Clone(),
|
||||
// clone intermediate query.
|
||||
sql: _q.sql.Clone(),
|
||||
path: _q.path,
|
||||
}
|
||||
}
|
||||
|
||||
// WithUser tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "user" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *UserRoleQuery) WithUser(opts ...func(*UserQuery)) *UserRoleQuery {
|
||||
query := (&UserClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withUser = query
|
||||
return _q
|
||||
}
|
||||
|
||||
// WithRole tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "role" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *UserRoleQuery) WithRole(opts ...func(*RoleQuery)) *UserRoleQuery {
|
||||
query := (&RoleClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withRole = query
|
||||
return _q
|
||||
}
|
||||
|
||||
// GroupBy is used to group vertices by one or more fields/columns.
|
||||
// It is often used with aggregate functions, like: count, max, mean, min, sum.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// UserID string `json:"user_id,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.UserRole.Query().
|
||||
// GroupBy(userrole.FieldUserID).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *UserRoleQuery) GroupBy(field string, fields ...string) *UserRoleGroupBy {
|
||||
_q.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &UserRoleGroupBy{build: _q}
|
||||
grbuild.flds = &_q.ctx.Fields
|
||||
grbuild.label = userrole.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 {
|
||||
// UserID string `json:"user_id,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.UserRole.Query().
|
||||
// Select(userrole.FieldUserID).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *UserRoleQuery) Select(fields ...string) *UserRoleSelect {
|
||||
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
|
||||
sbuild := &UserRoleSelect{UserRoleQuery: _q}
|
||||
sbuild.label = userrole.Label
|
||||
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a UserRoleSelect configured with the given aggregations.
|
||||
func (_q *UserRoleQuery) Aggregate(fns ...AggregateFunc) *UserRoleSelect {
|
||||
return _q.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (_q *UserRoleQuery) prepareQuery(ctx context.Context) error {
|
||||
for _, inter := range _q.inters {
|
||||
if inter == nil {
|
||||
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
|
||||
}
|
||||
if trv, ok := inter.(Traverser); ok {
|
||||
if err := trv.Traverse(ctx, _q); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, f := range _q.ctx.Fields {
|
||||
if !userrole.ValidColumn(f) {
|
||||
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
}
|
||||
if _q.path != nil {
|
||||
prev, err := _q.path(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_q.sql = prev
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *UserRoleQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserRole, error) {
|
||||
var (
|
||||
nodes = []*UserRole{}
|
||||
withFKs = _q.withFKs
|
||||
_spec = _q.querySpec()
|
||||
loadedTypes = [2]bool{
|
||||
_q.withUser != nil,
|
||||
_q.withRole != nil,
|
||||
}
|
||||
)
|
||||
if withFKs {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, userrole.ForeignKeys...)
|
||||
}
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*UserRole).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &UserRole{config: _q.config}
|
||||
nodes = append(nodes, node)
|
||||
node.Edges.loadedTypes = loadedTypes
|
||||
return node.assignValues(columns, values)
|
||||
}
|
||||
for i := range hooks {
|
||||
hooks[i](ctx, _spec)
|
||||
}
|
||||
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nodes, nil
|
||||
}
|
||||
if query := _q.withUser; query != nil {
|
||||
if err := _q.loadUser(ctx, query, nodes, nil,
|
||||
func(n *UserRole, e *User) { n.Edges.User = e }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if query := _q.withRole; query != nil {
|
||||
if err := _q.loadRole(ctx, query, nodes, nil,
|
||||
func(n *UserRole, e *Role) { n.Edges.Role = e }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (_q *UserRoleQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*UserRole, init func(*UserRole), assign func(*UserRole, *User)) error {
|
||||
ids := make([]string, 0, len(nodes))
|
||||
nodeids := make(map[string][]*UserRole)
|
||||
for i := range nodes {
|
||||
fk := nodes[i].UserID
|
||||
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_id" returned %v`, n.ID)
|
||||
}
|
||||
for i := range nodes {
|
||||
assign(nodes[i], n)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (_q *UserRoleQuery) loadRole(ctx context.Context, query *RoleQuery, nodes []*UserRole, init func(*UserRole), assign func(*UserRole, *Role)) error {
|
||||
ids := make([]string, 0, len(nodes))
|
||||
nodeids := make(map[string][]*UserRole)
|
||||
for i := range nodes {
|
||||
fk := nodes[i].RoleID
|
||||
if _, ok := nodeids[fk]; !ok {
|
||||
ids = append(ids, fk)
|
||||
}
|
||||
nodeids[fk] = append(nodeids[fk], nodes[i])
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
query.Where(role.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 "role_id" returned %v`, n.ID)
|
||||
}
|
||||
for i := range nodes {
|
||||
assign(nodes[i], n)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *UserRoleQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := _q.querySpec()
|
||||
_spec.Node.Columns = _q.ctx.Fields
|
||||
if len(_q.ctx.Fields) > 0 {
|
||||
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
|
||||
}
|
||||
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
|
||||
}
|
||||
|
||||
func (_q *UserRoleQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := sqlgraph.NewQuerySpec(userrole.Table, userrole.Columns, sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt))
|
||||
_spec.From = _q.sql
|
||||
if unique := _q.ctx.Unique; unique != nil {
|
||||
_spec.Unique = *unique
|
||||
} else if _q.path != nil {
|
||||
_spec.Unique = true
|
||||
}
|
||||
if fields := _q.ctx.Fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, userrole.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != userrole.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
if _q.withUser != nil {
|
||||
_spec.Node.AddColumnOnce(userrole.FieldUserID)
|
||||
}
|
||||
if _q.withRole != nil {
|
||||
_spec.Node.AddColumnOnce(userrole.FieldRoleID)
|
||||
}
|
||||
}
|
||||
if ps := _q.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit := _q.ctx.Limit; limit != nil {
|
||||
_spec.Limit = *limit
|
||||
}
|
||||
if offset := _q.ctx.Offset; offset != nil {
|
||||
_spec.Offset = *offset
|
||||
}
|
||||
if ps := _q.order; len(ps) > 0 {
|
||||
_spec.Order = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
return _spec
|
||||
}
|
||||
|
||||
func (_q *UserRoleQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(_q.driver.Dialect())
|
||||
t1 := builder.Table(userrole.Table)
|
||||
columns := _q.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = userrole.Columns
|
||||
}
|
||||
selector := builder.Select(t1.Columns(columns...)...).From(t1)
|
||||
if _q.sql != nil {
|
||||
selector = _q.sql
|
||||
selector.Select(selector.Columns(columns...)...)
|
||||
}
|
||||
if _q.ctx.Unique != nil && *_q.ctx.Unique {
|
||||
selector.Distinct()
|
||||
}
|
||||
for _, p := range _q.predicates {
|
||||
p(selector)
|
||||
}
|
||||
for _, p := range _q.order {
|
||||
p(selector)
|
||||
}
|
||||
if offset := _q.ctx.Offset; offset != nil {
|
||||
// limit is mandatory for offset clause. We start
|
||||
// with default value, and override it below if needed.
|
||||
selector.Offset(*offset).Limit(math.MaxInt32)
|
||||
}
|
||||
if limit := _q.ctx.Limit; limit != nil {
|
||||
selector.Limit(*limit)
|
||||
}
|
||||
return selector
|
||||
}
|
||||
|
||||
// UserRoleGroupBy is the group-by builder for UserRole entities.
|
||||
type UserRoleGroupBy struct {
|
||||
selector
|
||||
build *UserRoleQuery
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (_g *UserRoleGroupBy) Aggregate(fns ...AggregateFunc) *UserRoleGroupBy {
|
||||
_g.fns = append(_g.fns, fns...)
|
||||
return _g
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_g *UserRoleGroupBy) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
|
||||
if err := _g.build.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*UserRoleQuery, *UserRoleGroupBy](ctx, _g.build, _g, _g.build.inters, v)
|
||||
}
|
||||
|
||||
func (_g *UserRoleGroupBy) sqlScan(ctx context.Context, root *UserRoleQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx).Select()
|
||||
aggregation := make([]string, 0, len(_g.fns))
|
||||
for _, fn := range _g.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
if len(selector.SelectedColumns()) == 0 {
|
||||
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
|
||||
for _, f := range *_g.flds {
|
||||
columns = append(columns, selector.C(f))
|
||||
}
|
||||
columns = append(columns, aggregation...)
|
||||
selector.Select(columns...)
|
||||
}
|
||||
selector.GroupBy(selector.Columns(*_g.flds...)...)
|
||||
if err := selector.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
|
||||
// UserRoleSelect is the builder for selecting fields of UserRole entities.
|
||||
type UserRoleSelect struct {
|
||||
*UserRoleQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (_s *UserRoleSelect) Aggregate(fns ...AggregateFunc) *UserRoleSelect {
|
||||
_s.fns = append(_s.fns, fns...)
|
||||
return _s
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_s *UserRoleSelect) Scan(ctx context.Context, v any) error {
|
||||
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
|
||||
if err := _s.prepareQuery(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return scanWithInterceptors[*UserRoleQuery, *UserRoleSelect](ctx, _s.UserRoleQuery, _s, _s.inters, v)
|
||||
}
|
||||
|
||||
func (_s *UserRoleSelect) sqlScan(ctx context.Context, root *UserRoleQuery, v any) error {
|
||||
selector := root.sqlQuery(ctx)
|
||||
aggregation := make([]string, 0, len(_s.fns))
|
||||
for _, fn := range _s.fns {
|
||||
aggregation = append(aggregation, fn(selector))
|
||||
}
|
||||
switch n := len(*_s.selector.flds); {
|
||||
case n == 0 && len(aggregation) > 0:
|
||||
selector.Select(aggregation...)
|
||||
case n != 0 && len(aggregation) > 0:
|
||||
selector.AppendSelect(aggregation...)
|
||||
}
|
||||
rows := &sql.Rows{}
|
||||
query, args := selector.Query()
|
||||
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
return sql.ScanSlice(rows, v)
|
||||
}
|
||||
421
internal/ent/userrole_update.go
Normal file
421
internal/ent/userrole_update.go
Normal file
@@ -0,0 +1,421 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/predicate"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/role"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/user"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent/userrole"
|
||||
)
|
||||
|
||||
// UserRoleUpdate is the builder for updating UserRole entities.
|
||||
type UserRoleUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *UserRoleMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the UserRoleUpdate builder.
|
||||
func (_u *UserRoleUpdate) Where(ps ...predicate.UserRole) *UserRoleUpdate {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetUserID sets the "user_id" field.
|
||||
func (_u *UserRoleUpdate) SetUserID(v string) *UserRoleUpdate {
|
||||
_u.mutation.SetUserID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableUserID sets the "user_id" field if the given value is not nil.
|
||||
func (_u *UserRoleUpdate) SetNillableUserID(v *string) *UserRoleUpdate {
|
||||
if v != nil {
|
||||
_u.SetUserID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetRoleID sets the "role_id" field.
|
||||
func (_u *UserRoleUpdate) SetRoleID(v string) *UserRoleUpdate {
|
||||
_u.mutation.SetRoleID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableRoleID sets the "role_id" field if the given value is not nil.
|
||||
func (_u *UserRoleUpdate) SetNillableRoleID(v *string) *UserRoleUpdate {
|
||||
if v != nil {
|
||||
_u.SetRoleID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetUser sets the "user" edge to the User entity.
|
||||
func (_u *UserRoleUpdate) SetUser(v *User) *UserRoleUpdate {
|
||||
return _u.SetUserID(v.ID)
|
||||
}
|
||||
|
||||
// SetRole sets the "role" edge to the Role entity.
|
||||
func (_u *UserRoleUpdate) SetRole(v *Role) *UserRoleUpdate {
|
||||
return _u.SetRoleID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the UserRoleMutation object of the builder.
|
||||
func (_u *UserRoleUpdate) Mutation() *UserRoleMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearUser clears the "user" edge to the User entity.
|
||||
func (_u *UserRoleUpdate) ClearUser() *UserRoleUpdate {
|
||||
_u.mutation.ClearUser()
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearRole clears the "role" edge to the Role entity.
|
||||
func (_u *UserRoleUpdate) ClearRole() *UserRoleUpdate {
|
||||
_u.mutation.ClearRole()
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (_u *UserRoleUpdate) Save(ctx context.Context) (int, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *UserRoleUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_u *UserRoleUpdate) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *UserRoleUpdate) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *UserRoleUpdate) check() error {
|
||||
if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "UserRole.user"`)
|
||||
}
|
||||
if _u.mutation.RoleCleared() && len(_u.mutation.RoleIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "UserRole.role"`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *UserRoleUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(userrole.Table, userrole.Columns, sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt))
|
||||
if ps := _u.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if _u.mutation.UserCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: userrole.UserTable,
|
||||
Columns: []string{userrole.UserColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.UserIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: userrole.UserTable,
|
||||
Columns: []string{userrole.UserColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.RoleCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: userrole.RoleTable,
|
||||
Columns: []string{userrole.RoleColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RoleIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: userrole.RoleTable,
|
||||
Columns: []string{userrole.RoleColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
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{userrole.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
// UserRoleUpdateOne is the builder for updating a single UserRole entity.
|
||||
type UserRoleUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *UserRoleMutation
|
||||
}
|
||||
|
||||
// SetUserID sets the "user_id" field.
|
||||
func (_u *UserRoleUpdateOne) SetUserID(v string) *UserRoleUpdateOne {
|
||||
_u.mutation.SetUserID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableUserID sets the "user_id" field if the given value is not nil.
|
||||
func (_u *UserRoleUpdateOne) SetNillableUserID(v *string) *UserRoleUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetUserID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetRoleID sets the "role_id" field.
|
||||
func (_u *UserRoleUpdateOne) SetRoleID(v string) *UserRoleUpdateOne {
|
||||
_u.mutation.SetRoleID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableRoleID sets the "role_id" field if the given value is not nil.
|
||||
func (_u *UserRoleUpdateOne) SetNillableRoleID(v *string) *UserRoleUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetRoleID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetUser sets the "user" edge to the User entity.
|
||||
func (_u *UserRoleUpdateOne) SetUser(v *User) *UserRoleUpdateOne {
|
||||
return _u.SetUserID(v.ID)
|
||||
}
|
||||
|
||||
// SetRole sets the "role" edge to the Role entity.
|
||||
func (_u *UserRoleUpdateOne) SetRole(v *Role) *UserRoleUpdateOne {
|
||||
return _u.SetRoleID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the UserRoleMutation object of the builder.
|
||||
func (_u *UserRoleUpdateOne) Mutation() *UserRoleMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearUser clears the "user" edge to the User entity.
|
||||
func (_u *UserRoleUpdateOne) ClearUser() *UserRoleUpdateOne {
|
||||
_u.mutation.ClearUser()
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearRole clears the "role" edge to the Role entity.
|
||||
func (_u *UserRoleUpdateOne) ClearRole() *UserRoleUpdateOne {
|
||||
_u.mutation.ClearRole()
|
||||
return _u
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the UserRoleUpdate builder.
|
||||
func (_u *UserRoleUpdateOne) Where(ps ...predicate.UserRole) *UserRoleUpdateOne {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Select allows selecting one or more fields (columns) of the returned entity.
|
||||
// The default is selecting all fields defined in the entity schema.
|
||||
func (_u *UserRoleUpdateOne) Select(field string, fields ...string) *UserRoleUpdateOne {
|
||||
_u.fields = append([]string{field}, fields...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated UserRole entity.
|
||||
func (_u *UserRoleUpdateOne) Save(ctx context.Context) (*UserRole, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *UserRoleUpdateOne) SaveX(ctx context.Context) *UserRole {
|
||||
node, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (_u *UserRoleUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *UserRoleUpdateOne) ExecX(ctx context.Context) {
|
||||
if err := _u.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *UserRoleUpdateOne) check() error {
|
||||
if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "UserRole.user"`)
|
||||
}
|
||||
if _u.mutation.RoleCleared() && len(_u.mutation.RoleIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "UserRole.role"`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *UserRoleUpdateOne) sqlSave(ctx context.Context) (_node *UserRole, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(userrole.Table, userrole.Columns, sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt))
|
||||
id, ok := _u.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "UserRole.id" for update`)}
|
||||
}
|
||||
_spec.Node.ID.Value = id
|
||||
if fields := _u.fields; len(fields) > 0 {
|
||||
_spec.Node.Columns = make([]string, 0, len(fields))
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, userrole.FieldID)
|
||||
for _, f := range fields {
|
||||
if !userrole.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != userrole.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
if ps := _u.mutation.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
for i := range ps {
|
||||
ps[i](selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
if _u.mutation.UserCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: userrole.UserTable,
|
||||
Columns: []string{userrole.UserColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.UserIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: userrole.UserTable,
|
||||
Columns: []string{userrole.UserColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.RoleCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: userrole.RoleTable,
|
||||
Columns: []string{userrole.RoleColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RoleIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: false,
|
||||
Table: userrole.RoleTable,
|
||||
Columns: []string{userrole.RoleColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
_node = &UserRole{config: _u.config}
|
||||
_spec.Assign = _node.assignValues
|
||||
_spec.ScanValues = _node.scanValues
|
||||
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{userrole.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
165
internal/errorbus/channel_bus.go
Normal file
165
internal/errorbus/channel_bus.go
Normal file
@@ -0,0 +1,165 @@
|
||||
package errorbus
|
||||
|
||||
import (
|
||||
"context"
|
||||
"runtime"
|
||||
"sync"
|
||||
|
||||
"git.dcentral.systems/toolz/goplt/pkg/errorbus"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
||||
)
|
||||
|
||||
// ChannelBus implements a channel-based error bus.
|
||||
type ChannelBus struct {
|
||||
errors chan errorWithContext
|
||||
logger logger.Logger
|
||||
done chan struct{}
|
||||
wg sync.WaitGroup
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
type errorWithContext struct {
|
||||
err error
|
||||
ctx context.Context
|
||||
stack []byte
|
||||
}
|
||||
|
||||
// NewChannelBus creates a new channel-based error bus.
|
||||
func NewChannelBus(log logger.Logger, bufferSize int) *ChannelBus {
|
||||
if bufferSize <= 0 {
|
||||
bufferSize = 100
|
||||
}
|
||||
|
||||
bus := &ChannelBus{
|
||||
errors: make(chan errorWithContext, bufferSize),
|
||||
logger: log,
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
|
||||
// Start background consumer
|
||||
bus.wg.Add(1)
|
||||
go bus.consume()
|
||||
|
||||
return bus
|
||||
}
|
||||
|
||||
// Publish publishes an error to the error bus.
|
||||
func (b *ChannelBus) Publish(ctx context.Context, err error) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Capture stack trace
|
||||
stack := make([]byte, 4096)
|
||||
n := runtime.Stack(stack, false)
|
||||
stack = stack[:n]
|
||||
|
||||
select {
|
||||
case b.errors <- errorWithContext{
|
||||
err: err,
|
||||
ctx: ctx,
|
||||
stack: stack,
|
||||
}:
|
||||
// Successfully queued
|
||||
default:
|
||||
// Channel is full, log directly to avoid blocking
|
||||
b.logger.Error("Error bus channel full, logging directly",
|
||||
logger.String("error", err.Error()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// consume consumes errors from the channel and logs them.
|
||||
func (b *ChannelBus) consume() {
|
||||
defer b.wg.Done()
|
||||
|
||||
for {
|
||||
select {
|
||||
case errCtx := <-b.errors:
|
||||
b.handleError(errCtx)
|
||||
case <-b.done:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleError handles a single error by logging it with context.
|
||||
func (b *ChannelBus) handleError(errCtx errorWithContext) {
|
||||
fields := []logger.Field{
|
||||
logger.String("error", errCtx.err.Error()),
|
||||
}
|
||||
|
||||
// Extract request ID from context
|
||||
if requestID := extractRequestID(errCtx.ctx); requestID != "" {
|
||||
fields = append(fields, logger.String("request_id", requestID))
|
||||
}
|
||||
|
||||
// Extract user ID from context
|
||||
if userID := extractUserID(errCtx.ctx); userID != "" {
|
||||
fields = append(fields, logger.String("user_id", userID))
|
||||
}
|
||||
|
||||
// Add stack trace for debugging
|
||||
if len(errCtx.stack) > 0 {
|
||||
fields = append(fields, logger.String("stack", string(errCtx.stack)))
|
||||
}
|
||||
|
||||
b.logger.Error("Error captured by error bus", fields...)
|
||||
|
||||
// TODO: In Epic 6, add Sentry integration here
|
||||
// if b.sentryClient != nil {
|
||||
// b.sentryClient.CaptureException(errCtx.err, ...)
|
||||
// }
|
||||
}
|
||||
|
||||
// extractRequestID extracts request ID from context.
|
||||
func extractRequestID(ctx context.Context) string {
|
||||
if ctx == nil {
|
||||
return ""
|
||||
}
|
||||
// Try common context key patterns
|
||||
if val := ctx.Value("request_id"); val != nil {
|
||||
if str, ok := val.(string); ok {
|
||||
return str
|
||||
}
|
||||
}
|
||||
if val := ctx.Value("RequestID"); val != nil {
|
||||
if str, ok := val.(string); ok {
|
||||
return str
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// extractUserID extracts user ID from context.
|
||||
func extractUserID(ctx context.Context) string {
|
||||
if ctx == nil {
|
||||
return ""
|
||||
}
|
||||
// Try common context key patterns
|
||||
if val := ctx.Value("user_id"); val != nil {
|
||||
if str, ok := val.(string); ok {
|
||||
return str
|
||||
}
|
||||
}
|
||||
if val := ctx.Value("UserID"); val != nil {
|
||||
if str, ok := val.(string); ok {
|
||||
return str
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Close closes the error bus and waits for all errors to be processed.
|
||||
func (b *ChannelBus) Close() error {
|
||||
b.once.Do(func() {
|
||||
close(b.done)
|
||||
})
|
||||
b.wg.Wait()
|
||||
close(b.errors)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Ensure ChannelBus implements ErrorPublisher
|
||||
var _ errorbus.ErrorPublisher = (*ChannelBus)(nil)
|
||||
|
||||
26
internal/health/database.go
Normal file
26
internal/health/database.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package health
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.dcentral.systems/toolz/goplt/internal/infra/database"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/health"
|
||||
)
|
||||
|
||||
// DatabaseChecker implements health checks for the database.
|
||||
type DatabaseChecker struct {
|
||||
client *database.Client
|
||||
}
|
||||
|
||||
// NewDatabaseChecker creates a new database health checker.
|
||||
func NewDatabaseChecker(client *database.Client) health.HealthChecker {
|
||||
return &DatabaseChecker{
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
|
||||
// Check performs a database health check.
|
||||
func (d *DatabaseChecker) Check(ctx context.Context) error {
|
||||
return d.client.Ping(ctx)
|
||||
}
|
||||
|
||||
74
internal/health/registry.go
Normal file
74
internal/health/registry.go
Normal file
@@ -0,0 +1,74 @@
|
||||
package health
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"git.dcentral.systems/toolz/goplt/pkg/health"
|
||||
)
|
||||
|
||||
// Registry manages health checkers.
|
||||
type Registry struct {
|
||||
checkers map[string]health.HealthChecker
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewRegistry creates a new health check registry.
|
||||
func NewRegistry() *Registry {
|
||||
return &Registry{
|
||||
checkers: make(map[string]health.HealthChecker),
|
||||
}
|
||||
}
|
||||
|
||||
// Register registers a health checker with the given name.
|
||||
func (r *Registry) Register(name string, checker health.HealthChecker) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.checkers[name] = checker
|
||||
}
|
||||
|
||||
// Check performs health checks for all registered checkers.
|
||||
func (r *Registry) Check(ctx context.Context) health.HealthStatus {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
components := make([]health.ComponentStatus, 0, len(r.checkers))
|
||||
overallStatus := health.StatusHealthy
|
||||
|
||||
for name, checker := range r.checkers {
|
||||
err := checker.Check(ctx)
|
||||
status := health.StatusHealthy
|
||||
errorMsg := ""
|
||||
|
||||
if err != nil {
|
||||
status = health.StatusUnhealthy
|
||||
errorMsg = err.Error()
|
||||
overallStatus = health.StatusUnhealthy
|
||||
}
|
||||
|
||||
components = append(components, health.ComponentStatus{
|
||||
Name: name,
|
||||
Status: status,
|
||||
Error: errorMsg,
|
||||
})
|
||||
}
|
||||
|
||||
return health.HealthStatus{
|
||||
Status: overallStatus,
|
||||
Components: components,
|
||||
}
|
||||
}
|
||||
|
||||
// LivenessCheck performs a basic liveness check (no dependencies).
|
||||
func (r *Registry) LivenessCheck(ctx context.Context) health.HealthStatus {
|
||||
// Liveness is always healthy if the service is running
|
||||
return health.HealthStatus{
|
||||
Status: health.StatusHealthy,
|
||||
}
|
||||
}
|
||||
|
||||
// ReadinessCheck performs a readiness check (includes dependency checks).
|
||||
func (r *Registry) ReadinessCheck(ctx context.Context) health.HealthStatus {
|
||||
return r.Check(ctx)
|
||||
}
|
||||
|
||||
87
internal/infra/database/client.go
Normal file
87
internal/infra/database/client.go
Normal file
@@ -0,0 +1,87 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect"
|
||||
entsql "entgo.io/ent/dialect/sql"
|
||||
"git.dcentral.systems/toolz/goplt/internal/ent"
|
||||
_ "github.com/lib/pq" // PostgreSQL driver
|
||||
)
|
||||
|
||||
// Client wraps the Ent client with additional functionality.
|
||||
type Client struct {
|
||||
*ent.Client
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
// Config holds database configuration.
|
||||
type Config struct {
|
||||
DSN string
|
||||
MaxConnections int
|
||||
MaxIdleConns int
|
||||
ConnMaxLifetime time.Duration
|
||||
ConnMaxIdleTime time.Duration
|
||||
}
|
||||
|
||||
// NewClient creates a new Ent client with connection pooling.
|
||||
func NewClient(cfg Config) (*Client, error) {
|
||||
// Open database connection
|
||||
db, err := sql.Open("postgres", cfg.DSN)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open database connection: %w", err)
|
||||
}
|
||||
|
||||
// Configure connection pool
|
||||
db.SetMaxOpenConns(cfg.MaxConnections)
|
||||
db.SetMaxIdleConns(cfg.MaxIdleConns)
|
||||
db.SetConnMaxLifetime(cfg.ConnMaxLifetime)
|
||||
db.SetConnMaxIdleTime(cfg.ConnMaxIdleTime)
|
||||
|
||||
// Test connection
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := db.PingContext(ctx); err != nil {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("failed to ping database: %w", err)
|
||||
}
|
||||
|
||||
// Create Ent driver
|
||||
drv := entsql.OpenDB(dialect.Postgres, db)
|
||||
|
||||
// Create Ent client
|
||||
entClient := ent.NewClient(ent.Driver(drv))
|
||||
|
||||
return &Client{
|
||||
Client: entClient,
|
||||
db: db,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Close closes the database connection.
|
||||
func (c *Client) Close() error {
|
||||
if err := c.Client.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.db.Close()
|
||||
}
|
||||
|
||||
// Migrate runs database migrations.
|
||||
func (c *Client) Migrate(ctx context.Context) error {
|
||||
return c.Client.Schema.Create(ctx)
|
||||
}
|
||||
|
||||
// Ping checks database connectivity.
|
||||
func (c *Client) Ping(ctx context.Context) error {
|
||||
return c.db.PingContext(ctx)
|
||||
}
|
||||
|
||||
// DB returns the underlying *sql.DB for advanced operations.
|
||||
func (c *Client) DB() *sql.DB {
|
||||
return c.db
|
||||
}
|
||||
|
||||
97
internal/metrics/metrics.go
Normal file
97
internal/metrics/metrics.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
)
|
||||
|
||||
// Metrics holds all Prometheus metrics.
|
||||
type Metrics struct {
|
||||
httpRequestDuration *prometheus.HistogramVec
|
||||
httpRequestTotal *prometheus.CounterVec
|
||||
httpErrorsTotal *prometheus.CounterVec
|
||||
registry *prometheus.Registry
|
||||
}
|
||||
|
||||
// NewMetrics creates a new metrics registry with all metrics.
|
||||
func NewMetrics() *Metrics {
|
||||
registry := prometheus.NewRegistry()
|
||||
|
||||
m := &Metrics{
|
||||
registry: registry,
|
||||
httpRequestDuration: prometheus.NewHistogramVec(
|
||||
prometheus.HistogramOpts{
|
||||
Name: "http_request_duration_seconds",
|
||||
Help: "HTTP request duration in seconds",
|
||||
Buckets: prometheus.DefBuckets,
|
||||
},
|
||||
[]string{"method", "path", "status"},
|
||||
),
|
||||
httpRequestTotal: prometheus.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Name: "http_requests_total",
|
||||
Help: "Total number of HTTP requests",
|
||||
},
|
||||
[]string{"method", "path", "status"},
|
||||
),
|
||||
httpErrorsTotal: prometheus.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Name: "http_errors_total",
|
||||
Help: "Total number of HTTP errors",
|
||||
},
|
||||
[]string{"method", "path", "status"},
|
||||
),
|
||||
}
|
||||
|
||||
// Register all metrics
|
||||
registry.MustRegister(m.httpRequestDuration)
|
||||
registry.MustRegister(m.httpRequestTotal)
|
||||
registry.MustRegister(m.httpErrorsTotal)
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
// HTTPMiddleware returns a Gin middleware for collecting HTTP metrics.
|
||||
func (m *Metrics) HTTPMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
start := time.Now()
|
||||
|
||||
// Process request
|
||||
c.Next()
|
||||
|
||||
// Calculate duration
|
||||
duration := time.Since(start).Seconds()
|
||||
|
||||
// Get request details
|
||||
method := c.Request.Method
|
||||
path := c.FullPath()
|
||||
if path == "" {
|
||||
path = c.Request.URL.Path
|
||||
}
|
||||
status := c.Writer.Status()
|
||||
|
||||
// Record metrics
|
||||
m.httpRequestDuration.WithLabelValues(method, path, http.StatusText(status)).Observe(duration)
|
||||
m.httpRequestTotal.WithLabelValues(method, path, http.StatusText(status)).Inc()
|
||||
|
||||
// Record errors (4xx and 5xx)
|
||||
if status >= 400 {
|
||||
m.httpErrorsTotal.WithLabelValues(method, path, http.StatusText(status)).Inc()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handler returns an HTTP handler for the /metrics endpoint.
|
||||
func (m *Metrics) Handler() http.Handler {
|
||||
return promhttp.HandlerFor(m.registry, promhttp.HandlerOpts{})
|
||||
}
|
||||
|
||||
// Registry returns the Prometheus registry.
|
||||
func (m *Metrics) Registry() *prometheus.Registry {
|
||||
return m.registry
|
||||
}
|
||||
|
||||
141
internal/server/middleware.go
Normal file
141
internal/server/middleware.go
Normal file
@@ -0,0 +1,141 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/errorbus"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
requestIDKey = "request_id"
|
||||
userIDKey = "user_id"
|
||||
)
|
||||
|
||||
// RequestIDMiddleware generates a unique request ID for each request.
|
||||
func RequestIDMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
requestID := c.GetHeader("X-Request-ID")
|
||||
if requestID == "" {
|
||||
requestID = uuid.New().String()
|
||||
}
|
||||
|
||||
c.Set(requestIDKey, requestID)
|
||||
c.Header("X-Request-ID", requestID)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// LoggingMiddleware logs all HTTP requests with structured logging.
|
||||
func LoggingMiddleware(log logger.Logger) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
start := time.Now()
|
||||
path := c.Request.URL.Path
|
||||
method := c.Request.Method
|
||||
|
||||
// Process request
|
||||
c.Next()
|
||||
|
||||
// Calculate duration
|
||||
duration := time.Since(start)
|
||||
|
||||
// Get request ID from context
|
||||
requestID, _ := c.Get(requestIDKey)
|
||||
requestIDStr := ""
|
||||
if id, ok := requestID.(string); ok {
|
||||
requestIDStr = id
|
||||
}
|
||||
|
||||
// Log request
|
||||
log.Info("HTTP request",
|
||||
logger.String("method", method),
|
||||
logger.String("path", path),
|
||||
logger.Int("status", c.Writer.Status()),
|
||||
logger.Any("duration_ms", duration.Milliseconds()),
|
||||
logger.String("request_id", requestIDStr),
|
||||
logger.String("ip", c.ClientIP()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// PanicRecoveryMiddleware recovers from panics and publishes them to the error bus.
|
||||
func PanicRecoveryMiddleware(errorBus errorbus.ErrorPublisher) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
// Capture stack trace
|
||||
stack := make([]byte, 4096)
|
||||
n := runtime.Stack(stack, false)
|
||||
stack = stack[:n]
|
||||
|
||||
// Get request ID from context
|
||||
requestID, _ := c.Get(requestIDKey)
|
||||
ctx := context.WithValue(context.Background(), "request_id", requestID)
|
||||
|
||||
// Create error
|
||||
var panicErr error
|
||||
if e, ok := err.(error); ok {
|
||||
panicErr = e
|
||||
} else {
|
||||
panicErr = &panicError{value: err, stack: stack}
|
||||
}
|
||||
|
||||
// Publish to error bus
|
||||
errorBus.Publish(ctx, panicErr)
|
||||
|
||||
// Return error response
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Internal server error",
|
||||
})
|
||||
|
||||
c.Abort()
|
||||
}
|
||||
}()
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// panicError wraps a panic value as an error.
|
||||
type panicError struct {
|
||||
value interface{}
|
||||
stack []byte
|
||||
}
|
||||
|
||||
func (e *panicError) Error() string {
|
||||
return "panic recovered"
|
||||
}
|
||||
|
||||
// CORSMiddleware provides CORS support.
|
||||
func CORSMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE, PATCH")
|
||||
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// TimeoutMiddleware sets a request timeout.
|
||||
func TimeoutMiddleware(timeout time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), timeout)
|
||||
defer cancel()
|
||||
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
131
internal/server/server.go
Normal file
131
internal/server/server.go
Normal file
@@ -0,0 +1,131 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"git.dcentral.systems/toolz/goplt/internal/health"
|
||||
"git.dcentral.systems/toolz/goplt/internal/metrics"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/config"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/errorbus"
|
||||
"git.dcentral.systems/toolz/goplt/pkg/logger"
|
||||
)
|
||||
|
||||
// Server wraps the HTTP server and Gin router.
|
||||
type Server struct {
|
||||
httpServer *http.Server
|
||||
router *gin.Engine
|
||||
}
|
||||
|
||||
// NewServer creates a new HTTP server with all middleware and routes.
|
||||
func NewServer(
|
||||
cfg config.ConfigProvider,
|
||||
log logger.Logger,
|
||||
healthRegistry *health.Registry,
|
||||
metricsRegistry *metrics.Metrics,
|
||||
errorBus errorbus.ErrorPublisher,
|
||||
) (*Server, error) {
|
||||
// Set Gin mode
|
||||
env := cfg.GetString("environment")
|
||||
if env == "production" {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
}
|
||||
|
||||
router := gin.New()
|
||||
|
||||
// Add middleware (order matters!)
|
||||
router.Use(RequestIDMiddleware())
|
||||
router.Use(LoggingMiddleware(log))
|
||||
router.Use(PanicRecoveryMiddleware(errorBus))
|
||||
router.Use(metricsRegistry.HTTPMiddleware())
|
||||
router.Use(CORSMiddleware())
|
||||
|
||||
// Request timeout middleware (optional, can be configured per route if needed)
|
||||
// router.Use(TimeoutMiddleware(timeout))
|
||||
|
||||
// Register core routes
|
||||
registerRoutes(router, healthRegistry, metricsRegistry)
|
||||
|
||||
// Get server configuration
|
||||
port := cfg.GetInt("server.port")
|
||||
if port == 0 {
|
||||
port = 8080
|
||||
}
|
||||
host := cfg.GetString("server.host")
|
||||
if host == "" {
|
||||
host = "0.0.0.0"
|
||||
}
|
||||
|
||||
readTimeout := cfg.GetDuration("server.read_timeout")
|
||||
if readTimeout == 0 {
|
||||
readTimeout = 30 * time.Second
|
||||
}
|
||||
|
||||
writeTimeout := cfg.GetDuration("server.write_timeout")
|
||||
if writeTimeout == 0 {
|
||||
writeTimeout = 30 * time.Second
|
||||
}
|
||||
|
||||
addr := fmt.Sprintf("%s:%d", host, port)
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: router,
|
||||
ReadTimeout: readTimeout,
|
||||
WriteTimeout: writeTimeout,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
|
||||
return &Server{
|
||||
httpServer: httpServer,
|
||||
router: router,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// registerRoutes registers all core routes.
|
||||
func registerRoutes(
|
||||
router *gin.Engine,
|
||||
healthRegistry *health.Registry,
|
||||
metricsRegistry *metrics.Metrics,
|
||||
) {
|
||||
// Health endpoints
|
||||
router.GET("/healthz", func(c *gin.Context) {
|
||||
status := healthRegistry.LivenessCheck(c.Request.Context())
|
||||
if status.Status == "healthy" {
|
||||
c.JSON(http.StatusOK, status)
|
||||
} else {
|
||||
c.JSON(http.StatusServiceUnavailable, status)
|
||||
}
|
||||
})
|
||||
|
||||
router.GET("/ready", func(c *gin.Context) {
|
||||
status := healthRegistry.ReadinessCheck(c.Request.Context())
|
||||
if status.Status == "healthy" {
|
||||
c.JSON(http.StatusOK, status)
|
||||
} else {
|
||||
c.JSON(http.StatusServiceUnavailable, status)
|
||||
}
|
||||
})
|
||||
|
||||
// Metrics endpoint
|
||||
router.GET("/metrics", gin.WrapH(metricsRegistry.Handler()))
|
||||
}
|
||||
|
||||
// Start starts the HTTP server.
|
||||
func (s *Server) Start() error {
|
||||
return s.httpServer.ListenAndServe()
|
||||
}
|
||||
|
||||
// Shutdown gracefully shuts down the HTTP server.
|
||||
func (s *Server) Shutdown(ctx context.Context) error {
|
||||
return s.httpServer.Shutdown(ctx)
|
||||
}
|
||||
|
||||
// Router returns the Gin router (for adding additional routes).
|
||||
func (s *Server) Router() *gin.Engine {
|
||||
return s.router
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user