chore: make gazelle run with go generate

This commit is contained in:
41666 2020-09-15 23:08:29 -04:00
parent 94eec4e10d
commit bb83575308
27 changed files with 370 additions and 482 deletions

View file

@ -1,23 +0,0 @@
load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
go_library(
name = "db-tool_lib",
srcs = [
"import.go",
"migrate.go",
],
importpath = "github.com/roleypoly/roleypoly/src/db/cmd/db-tool",
visibility = ["//visibility:private"],
deps = [
"@com_github_lib_pq//:pq",
"@com_github_roleypoly_db//ent",
"@com_github_roleypoly_db//ent/migrate",
"@com_github_roleypoly_db//ent/schema",
],
)
go_binary(
name = "db-tool",
embed = [":db-tool_lib"],
visibility = ["//visibility:public"],
)

View file

@ -1,59 +0,0 @@
# Accept the Go version for the image to be set as a build argument.
# Default to Go 1.12
ARG GO_VERSION=1.13
# First stage: build the executable.
FROM --platform=$BUILDPLATFORM golang:${GO_VERSION}-alpine AS builder
ARG GOPROXY
ARG BUILDPLATFORM
ARG TARGETARCH
ARG TARGETOS
ENV GOPROXY ${GOPROXY}
ENV GOOS ${TARGETOS}
ENV GOARCH ${TARGETARCH}
# Create the user and group files that will be used in the running container to
# run the process as an unprivileged user.
RUN mkdir /user && \
echo 'nobody:x:65534:65534:nobody:/:' > /user/passwd && \
echo 'nobody:x:65534:' > /user/group
# Install the Certificate-Authority certificates for the app to be able to make
# calls to HTTPS endpoints.
# Git is required for fetching the dependencies.
RUN apk add --no-cache ca-certificates git
# Set the working directory outside $GOPATH to enable the support for modules.
WORKDIR /src
# Fetch dependencies first; they are less susceptible to change on every build
# and will therefore be cached for speeding up the next build
COPY ./go.mod ./go.sum ./
RUN go mod download
# Import the code from the context.
COPY ./ ./
# Build the executable to `/app`. Mark the build as statically linked.
RUN CGO_ENABLED=0 go build \
-installsuffix 'static' \
-o /app ./cmd/db-tool
# Final stage: the running container.
FROM scratch AS final
# Import the user and group files from the first stage.
COPY --from=builder /user/group /user/passwd /etc/
# Import the Certificate-Authority certificates for enabling HTTPS.
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
# Import the compiled executable from the first stage.
COPY --from=builder /app /app
# Perform any further action as an unprivileged user.
USER nobody:nobody
# Run the compiled binary.
ENTRYPOINT ["/app"]

View file

@ -1,14 +0,0 @@
version: '2'
services:
pg:
image: postgres:11-alpine
ports:
- 5432
volumes:
- './.data/pg:/var/lib/postgresql/data'
environment:
POSTGRES_PASSWORD: 19216801
POSTGRES_DB: roleypoly
POSTGRES_USER: roleypoly
POSTGRES_INITDB_ARGS: -A trust

View file

@ -1,104 +0,0 @@
package main
import (
"context"
"database/sql"
"log"
"os"
"time"
ent "github.com/roleypoly/db/ent"
"github.com/roleypoly/db/ent/schema"
)
type v1Category struct {
ID string `json:"id"`
Name string `json:"name"`
Roles []string `json:"roles"`
Hidden bool `json:"hidden"`
Type string `json:"type"`
Position int `json:"position"`
}
type v1Server struct {
ID string `json:"id"`
Categories []v1Category `json:"categories"`
Message string `json:"message"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func fromCategories(cats []v1Category) []schema.Category {
out := make([]schema.Category, len(cats))
for i, cat := range cats {
out[i] = schema.Category{
ID: cat.ID,
Name: cat.Name,
Hidden: cat.Hidden,
Type: cat.Type,
Position: cat.Position,
Roles: cat.Roles,
}
}
return out
}
func runImport(newDB *ent.Client, oldDB *sql.DB) {
ctx := ent.NewContext(context.Background(), newDB)
tx, err := newDB.Tx(ctx)
oldServers, err := oldDB.Query(`SELECT * FROM servers`)
if err != nil {
tx.Rollback()
log.Fatalln("query error", err)
}
defer oldServers.Close()
for oldServers.Next() == true {
var data v1Server
log.Printf("importing %s\n", data.ID)
err = oldServers.Scan(&data)
if err != nil {
tx.Rollback()
log.Fatalln("data scan error", err)
}
guild := tx.Guild.Create()
guild.SetMessage(data.Message).
SetSnowflake(data.ID).
SetCategories(fromCategories(data.Categories)).
SetCreateTime(data.CreatedAt)
ctx := ent.NewContext(context.Background(), newDB)
guild.SaveX(ctx)
}
err = tx.Commit()
if err != nil {
log.Fatalln("tx commit error", err)
}
}
func importFromV1() {
log.Println("Import from V1 starting.")
client, err := ent.Open("postgres", os.Getenv("DB_URL"))
if err != nil {
log.Fatalln(err)
}
defer client.Close()
oldClient, err := sql.Open("postgres", os.Getenv("OLD_DB_URL"))
if err != nil {
log.Fatalln(err)
}
defer oldClient.Close()
runImport(client, oldClient)
log.Println("Import from V1 finished.")
}

View file

@ -1,58 +0,0 @@
package main
import (
"context"
"log"
"os"
"time"
_ "github.com/lib/pq"
ent "github.com/roleypoly/db/ent"
"github.com/roleypoly/db/ent/migrate"
)
func retryMigrate(client *ent.Client) {
for i := 0; i < 10; i++ {
err := client.Schema.Create(context.Background(), migrate.WithGlobalUniqueID(true))
if err == nil {
return
}
log.Println("Migration failed --", err)
time.Sleep(2 * time.Second)
}
log.Fatalln("Migration failed after 20 seconds.")
return
}
func doMigrate() {
log.Println("Migrations starting.")
client, err := ent.Open("postgres", os.Getenv("DB_URL"))
if err != nil {
log.Fatalln(err)
}
defer client.Close()
retryMigrate(client)
log.Println("Migrations finished.")
}
func main() {
tool := os.Args[1]
if tool == "" {
tool = "migrate"
}
switch tool {
case "migrate":
doMigrate()
case "import":
importFromV1()
default:
log.Fatalln("supported tools: migrate, import")
}
}

View file

@ -42,6 +42,16 @@ var Columns = []string{
FieldExpiresAt,
}
// 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 (
// DefaultCreateTime holds the default value on creation for the create_time field.
DefaultCreateTime func() time.Time

View file

@ -93,14 +93,15 @@ func (cc *ChallengeCreate) Mutation() *ChallengeMutation {
// Save creates the Challenge in the database.
func (cc *ChallengeCreate) Save(ctx context.Context) (*Challenge, error) {
if err := cc.preSave(); err != nil {
return nil, err
}
var (
err error
node *Challenge
)
cc.defaults()
if len(cc.hooks) == 0 {
if err = cc.check(); err != nil {
return nil, err
}
node, err = cc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
@ -108,6 +109,9 @@ func (cc *ChallengeCreate) Save(ctx context.Context) (*Challenge, error) {
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = cc.check(); err != nil {
return nil, err
}
cc.mutation = mutation
node, err = cc.sqlSave(ctx)
mutation.done = true
@ -132,7 +136,8 @@ func (cc *ChallengeCreate) SaveX(ctx context.Context) *Challenge {
return v
}
func (cc *ChallengeCreate) preSave() error {
// defaults sets the default values of the builder before save.
func (cc *ChallengeCreate) defaults() {
if _, ok := cc.mutation.CreateTime(); !ok {
v := challenge.DefaultCreateTime()
cc.mutation.SetCreateTime(v)
@ -141,6 +146,20 @@ func (cc *ChallengeCreate) preSave() error {
v := challenge.DefaultUpdateTime()
cc.mutation.SetUpdateTime(v)
}
if _, ok := cc.mutation.ExpiresAt(); !ok {
v := challenge.DefaultExpiresAt()
cc.mutation.SetExpiresAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (cc *ChallengeCreate) check() error {
if _, ok := cc.mutation.CreateTime(); !ok {
return &ValidationError{Name: "create_time", err: errors.New("ent: missing required field \"create_time\"")}
}
if _, ok := cc.mutation.UpdateTime(); !ok {
return &ValidationError{Name: "update_time", err: errors.New("ent: missing required field \"update_time\"")}
}
if _, ok := cc.mutation.ChallengeID(); !ok {
return &ValidationError{Name: "challenge_id", err: errors.New("ent: missing required field \"challenge_id\"")}
}
@ -154,14 +173,13 @@ func (cc *ChallengeCreate) preSave() error {
return &ValidationError{Name: "magic", err: errors.New("ent: missing required field \"magic\"")}
}
if _, ok := cc.mutation.ExpiresAt(); !ok {
v := challenge.DefaultExpiresAt()
cc.mutation.SetExpiresAt(v)
return &ValidationError{Name: "expires_at", err: errors.New("ent: missing required field \"expires_at\"")}
}
return nil
}
func (cc *ChallengeCreate) sqlSave(ctx context.Context) (*Challenge, error) {
c, _spec := cc.createSpec()
_node, _spec := cc.createSpec()
if err := sqlgraph.CreateNode(ctx, cc.driver, _spec); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
@ -169,13 +187,13 @@ func (cc *ChallengeCreate) sqlSave(ctx context.Context) (*Challenge, error) {
return nil, err
}
id := _spec.ID.Value.(int64)
c.ID = int(id)
return c, nil
_node.ID = int(id)
return _node, nil
}
func (cc *ChallengeCreate) createSpec() (*Challenge, *sqlgraph.CreateSpec) {
var (
c = &Challenge{config: cc.config}
_node = &Challenge{config: cc.config}
_spec = &sqlgraph.CreateSpec{
Table: challenge.Table,
ID: &sqlgraph.FieldSpec{
@ -190,7 +208,7 @@ func (cc *ChallengeCreate) createSpec() (*Challenge, *sqlgraph.CreateSpec) {
Value: value,
Column: challenge.FieldCreateTime,
})
c.CreateTime = value
_node.CreateTime = value
}
if value, ok := cc.mutation.UpdateTime(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
@ -198,7 +216,7 @@ func (cc *ChallengeCreate) createSpec() (*Challenge, *sqlgraph.CreateSpec) {
Value: value,
Column: challenge.FieldUpdateTime,
})
c.UpdateTime = value
_node.UpdateTime = value
}
if value, ok := cc.mutation.ChallengeID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
@ -206,7 +224,7 @@ func (cc *ChallengeCreate) createSpec() (*Challenge, *sqlgraph.CreateSpec) {
Value: value,
Column: challenge.FieldChallengeID,
})
c.ChallengeID = value
_node.ChallengeID = value
}
if value, ok := cc.mutation.UserID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
@ -214,7 +232,7 @@ func (cc *ChallengeCreate) createSpec() (*Challenge, *sqlgraph.CreateSpec) {
Value: value,
Column: challenge.FieldUserID,
})
c.UserID = value
_node.UserID = value
}
if value, ok := cc.mutation.Human(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
@ -222,7 +240,7 @@ func (cc *ChallengeCreate) createSpec() (*Challenge, *sqlgraph.CreateSpec) {
Value: value,
Column: challenge.FieldHuman,
})
c.Human = value
_node.Human = value
}
if value, ok := cc.mutation.Magic(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
@ -230,7 +248,7 @@ func (cc *ChallengeCreate) createSpec() (*Challenge, *sqlgraph.CreateSpec) {
Value: value,
Column: challenge.FieldMagic,
})
c.Magic = value
_node.Magic = value
}
if value, ok := cc.mutation.ExpiresAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
@ -238,9 +256,9 @@ func (cc *ChallengeCreate) createSpec() (*Challenge, *sqlgraph.CreateSpec) {
Value: value,
Column: challenge.FieldExpiresAt,
})
c.ExpiresAt = value
_node.ExpiresAt = value
}
return c, _spec
return _node, _spec
}
// ChallengeCreateBulk is the builder for creating a bulk of Challenge entities.
@ -257,14 +275,15 @@ func (ccb *ChallengeCreateBulk) Save(ctx context.Context) ([]*Challenge, error)
for i := range ccb.builders {
func(i int, root context.Context) {
builder := ccb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
if err := builder.preSave(); err != nil {
return nil, err
}
mutation, ok := m.(*ChallengeMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error

View file

@ -54,23 +54,23 @@ func (cq *ChallengeQuery) Order(o ...OrderFunc) *ChallengeQuery {
// First returns the first Challenge entity in the query. Returns *NotFoundError when no challenge was found.
func (cq *ChallengeQuery) First(ctx context.Context) (*Challenge, error) {
cs, err := cq.Limit(1).All(ctx)
nodes, err := cq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(cs) == 0 {
if len(nodes) == 0 {
return nil, &NotFoundError{challenge.Label}
}
return cs[0], nil
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (cq *ChallengeQuery) FirstX(ctx context.Context) *Challenge {
c, err := cq.First(ctx)
node, err := cq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return c
return node
}
// FirstID returns the first Challenge id in the query. Returns *NotFoundError when no id was found.
@ -97,13 +97,13 @@ func (cq *ChallengeQuery) FirstXID(ctx context.Context) int {
// Only returns the only Challenge entity in the query, returns an error if not exactly one entity was returned.
func (cq *ChallengeQuery) Only(ctx context.Context) (*Challenge, error) {
cs, err := cq.Limit(2).All(ctx)
nodes, err := cq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(cs) {
switch len(nodes) {
case 1:
return cs[0], nil
return nodes[0], nil
case 0:
return nil, &NotFoundError{challenge.Label}
default:
@ -113,11 +113,11 @@ func (cq *ChallengeQuery) Only(ctx context.Context) (*Challenge, error) {
// OnlyX is like Only, but panics if an error occurs.
func (cq *ChallengeQuery) OnlyX(ctx context.Context) *Challenge {
c, err := cq.Only(ctx)
node, err := cq.Only(ctx)
if err != nil {
panic(err)
}
return c
return node
}
// OnlyID returns the only Challenge id in the query, returns an error if not exactly one id was returned.
@ -156,11 +156,11 @@ func (cq *ChallengeQuery) All(ctx context.Context) ([]*Challenge, error) {
// AllX is like All, but panics if an error occurs.
func (cq *ChallengeQuery) AllX(ctx context.Context) []*Challenge {
cs, err := cq.All(ctx)
nodes, err := cq.All(ctx)
if err != nil {
panic(err)
}
return cs
return nodes
}
// IDs executes the query and returns a list of Challenge ids.
@ -362,7 +362,7 @@ func (cq *ChallengeQuery) querySpec() *sqlgraph.QuerySpec {
if ps := cq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
ps[i](selector, challenge.ValidColumn)
}
}
}
@ -381,7 +381,7 @@ func (cq *ChallengeQuery) sqlQuery() *sql.Selector {
p(selector)
}
for _, p := range cq.order {
p(selector)
p(selector, challenge.ValidColumn)
}
if offset := cq.offset; offset != nil {
// limit is mandatory for offset clause. We start
@ -616,8 +616,17 @@ func (cgb *ChallengeGroupBy) BoolX(ctx context.Context) bool {
}
func (cgb *ChallengeGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range cgb.fields {
if !challenge.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := cgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := cgb.sqlQuery().Query()
query, args := selector.Query()
if err := cgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
@ -630,7 +639,7 @@ func (cgb *ChallengeGroupBy) sqlQuery() *sql.Selector {
columns := make([]string, 0, len(cgb.fields)+len(cgb.fns))
columns = append(columns, cgb.fields...)
for _, fn := range cgb.fns {
columns = append(columns, fn(selector))
columns = append(columns, fn(selector, challenge.ValidColumn))
}
return selector.Select(columns...).GroupBy(cgb.fields...)
}
@ -850,6 +859,11 @@ func (cs *ChallengeSelect) BoolX(ctx context.Context) bool {
}
func (cs *ChallengeSelect) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range cs.fields {
if !challenge.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for selection", f)}
}
}
rows := &sql.Rows{}
query, args := cs.sqlQuery().Query()
if err := cs.driver.Query(ctx, query, args, rows); err != nil {

View file

@ -34,14 +34,11 @@ func (cu *ChallengeUpdate) Mutation() *ChallengeMutation {
// Save executes the query and returns the number of rows/vertices matched by this operation.
func (cu *ChallengeUpdate) Save(ctx context.Context) (int, error) {
if _, ok := cu.mutation.UpdateTime(); !ok {
v := challenge.UpdateDefaultUpdateTime()
cu.mutation.SetUpdateTime(v)
}
var (
err error
affected int
)
cu.defaults()
if len(cu.hooks) == 0 {
affected, err = cu.sqlSave(ctx)
} else {
@ -87,6 +84,14 @@ func (cu *ChallengeUpdate) ExecX(ctx context.Context) {
}
}
// defaults sets the default values of the builder before save.
func (cu *ChallengeUpdate) defaults() {
if _, ok := cu.mutation.UpdateTime(); !ok {
v := challenge.UpdateDefaultUpdateTime()
cu.mutation.SetUpdateTime(v)
}
}
func (cu *ChallengeUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
@ -137,14 +142,11 @@ func (cuo *ChallengeUpdateOne) Mutation() *ChallengeMutation {
// Save executes the query and returns the updated entity.
func (cuo *ChallengeUpdateOne) Save(ctx context.Context) (*Challenge, error) {
if _, ok := cuo.mutation.UpdateTime(); !ok {
v := challenge.UpdateDefaultUpdateTime()
cuo.mutation.SetUpdateTime(v)
}
var (
err error
node *Challenge
)
cuo.defaults()
if len(cuo.hooks) == 0 {
node, err = cuo.sqlSave(ctx)
} else {
@ -170,11 +172,11 @@ func (cuo *ChallengeUpdateOne) Save(ctx context.Context) (*Challenge, error) {
// SaveX is like Save, but panics if an error occurs.
func (cuo *ChallengeUpdateOne) SaveX(ctx context.Context) *Challenge {
c, err := cuo.Save(ctx)
node, err := cuo.Save(ctx)
if err != nil {
panic(err)
}
return c
return node
}
// Exec executes the query on the entity.
@ -190,7 +192,15 @@ func (cuo *ChallengeUpdateOne) ExecX(ctx context.Context) {
}
}
func (cuo *ChallengeUpdateOne) sqlSave(ctx context.Context) (c *Challenge, err error) {
// defaults sets the default values of the builder before save.
func (cuo *ChallengeUpdateOne) defaults() {
if _, ok := cuo.mutation.UpdateTime(); !ok {
v := challenge.UpdateDefaultUpdateTime()
cuo.mutation.SetUpdateTime(v)
}
}
func (cuo *ChallengeUpdateOne) sqlSave(ctx context.Context) (_node *Challenge, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: challenge.Table,
@ -213,9 +223,9 @@ func (cuo *ChallengeUpdateOne) sqlSave(ctx context.Context) (c *Challenge, err e
Column: challenge.FieldUpdateTime,
})
}
c = &Challenge{config: cuo.config}
_spec.Assign = c.assignValues
_spec.ScanValues = c.scanValues()
_node = &Challenge{config: cuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues()
if err = sqlgraph.UpdateNode(ctx, cuo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{challenge.Label}
@ -224,5 +234,5 @@ func (cuo *ChallengeUpdateOne) sqlSave(ctx context.Context) (c *Challenge, err e
}
return nil, err
}
return c, nil
return _node, nil
}

View file

@ -206,11 +206,11 @@ func (c *ChallengeClient) Get(ctx context.Context, id int) (*Challenge, error) {
// GetX is like Get, but panics if an error occurs.
func (c *ChallengeClient) GetX(ctx context.Context, id int) *Challenge {
ch, err := c.Get(ctx, id)
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return ch
return obj
}
// Hooks returns the client hooks.
@ -294,11 +294,11 @@ func (c *GuildClient) Get(ctx context.Context, id int) (*Guild, error) {
// GetX is like Get, but panics if an error occurs.
func (c *GuildClient) GetX(ctx context.Context, id int) *Guild {
gu, err := c.Get(ctx, id)
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return gu
return obj
}
// Hooks returns the client hooks.
@ -382,11 +382,11 @@ func (c *SessionClient) Get(ctx context.Context, id int) (*Session, error) {
// GetX is like Get, but panics if an error occurs.
func (c *SessionClient) GetX(ctx context.Context, id int) *Session {
s, err := c.Get(ctx, id)
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return s
return obj
}
// Hooks returns the client hooks.

View file

@ -25,29 +25,37 @@ type (
MutateFunc = ent.MutateFunc
)
// OrderFunc applies an ordering on either graph traversal or sql selector.
type OrderFunc func(*sql.Selector)
// OrderFunc applies an ordering on the sql selector.
type OrderFunc func(*sql.Selector, func(string) bool)
// Asc applies the given fields in ASC order.
func Asc(fields ...string) OrderFunc {
return func(s *sql.Selector) {
return func(s *sql.Selector, check func(string) bool) {
for _, f := range fields {
s.OrderBy(sql.Asc(f))
if check(f) {
s.OrderBy(sql.Asc(f))
} else {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("invalid field %q for ordering", f)})
}
}
}
}
// Desc applies the given fields in DESC order.
func Desc(fields ...string) OrderFunc {
return func(s *sql.Selector) {
return func(s *sql.Selector, check func(string) bool) {
for _, f := range fields {
s.OrderBy(sql.Desc(f))
if check(f) {
s.OrderBy(sql.Desc(f))
} else {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("invalid field %q for ordering", f)})
}
}
}
}
// AggregateFunc applies an aggregation step on the group-by traversal/selector.
type AggregateFunc func(*sql.Selector) string
type AggregateFunc func(*sql.Selector, func(string) bool) string
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
//
@ -56,42 +64,58 @@ type AggregateFunc func(*sql.Selector) string
// Scan(ctx, &v)
//
func As(fn AggregateFunc, end string) AggregateFunc {
return func(s *sql.Selector) string {
return sql.As(fn(s), end)
return func(s *sql.Selector, check func(string) bool) string {
return sql.As(fn(s, check), end)
}
}
// Count applies the "count" aggregation function on each group.
func Count() AggregateFunc {
return func(s *sql.Selector) string {
return func(s *sql.Selector, _ func(string) bool) 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 {
return func(s *sql.Selector, check func(string) bool) string {
if !check(field) {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("invalid field %q for grouping", field)})
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 {
return func(s *sql.Selector, check func(string) bool) string {
if !check(field) {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("invalid field %q for grouping", field)})
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 {
return func(s *sql.Selector, check func(string) bool) string {
if !check(field) {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("invalid field %q for grouping", field)})
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 {
return func(s *sql.Selector, check func(string) bool) string {
if !check(field) {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("invalid field %q for grouping", field)})
return ""
}
return sql.Sum(s.C(field))
}
}
@ -109,7 +133,7 @@ func (e *ValidationError) Error() string {
// Unwrap implements the errors.Wrapper interface.
func (e *ValidationError) Unwrap() error {
return errors.Unwrap(e.err)
return e.err
}
// IsValidationError returns a boolean indicating whether the error is a validaton error.

View file

@ -39,6 +39,16 @@ var Columns = []string{
FieldEntitlements,
}
// 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 (
// DefaultCreateTime holds the default value on creation for the create_time field.
DefaultCreateTime func() time.Time

View file

@ -80,14 +80,15 @@ func (gc *GuildCreate) Mutation() *GuildMutation {
// Save creates the Guild in the database.
func (gc *GuildCreate) Save(ctx context.Context) (*Guild, error) {
if err := gc.preSave(); err != nil {
return nil, err
}
var (
err error
node *Guild
)
gc.defaults()
if len(gc.hooks) == 0 {
if err = gc.check(); err != nil {
return nil, err
}
node, err = gc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
@ -95,6 +96,9 @@ func (gc *GuildCreate) Save(ctx context.Context) (*Guild, error) {
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = gc.check(); err != nil {
return nil, err
}
gc.mutation = mutation
node, err = gc.sqlSave(ctx)
mutation.done = true
@ -119,7 +123,8 @@ func (gc *GuildCreate) SaveX(ctx context.Context) *Guild {
return v
}
func (gc *GuildCreate) preSave() error {
// defaults sets the default values of the builder before save.
func (gc *GuildCreate) defaults() {
if _, ok := gc.mutation.CreateTime(); !ok {
v := guild.DefaultCreateTime()
gc.mutation.SetCreateTime(v)
@ -128,6 +133,16 @@ func (gc *GuildCreate) preSave() error {
v := guild.DefaultUpdateTime()
gc.mutation.SetUpdateTime(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (gc *GuildCreate) check() error {
if _, ok := gc.mutation.CreateTime(); !ok {
return &ValidationError{Name: "create_time", err: errors.New("ent: missing required field \"create_time\"")}
}
if _, ok := gc.mutation.UpdateTime(); !ok {
return &ValidationError{Name: "update_time", err: errors.New("ent: missing required field \"update_time\"")}
}
if _, ok := gc.mutation.Snowflake(); !ok {
return &ValidationError{Name: "snowflake", err: errors.New("ent: missing required field \"snowflake\"")}
}
@ -144,7 +159,7 @@ func (gc *GuildCreate) preSave() error {
}
func (gc *GuildCreate) sqlSave(ctx context.Context) (*Guild, error) {
gu, _spec := gc.createSpec()
_node, _spec := gc.createSpec()
if err := sqlgraph.CreateNode(ctx, gc.driver, _spec); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
@ -152,13 +167,13 @@ func (gc *GuildCreate) sqlSave(ctx context.Context) (*Guild, error) {
return nil, err
}
id := _spec.ID.Value.(int64)
gu.ID = int(id)
return gu, nil
_node.ID = int(id)
return _node, nil
}
func (gc *GuildCreate) createSpec() (*Guild, *sqlgraph.CreateSpec) {
var (
gu = &Guild{config: gc.config}
_node = &Guild{config: gc.config}
_spec = &sqlgraph.CreateSpec{
Table: guild.Table,
ID: &sqlgraph.FieldSpec{
@ -173,7 +188,7 @@ func (gc *GuildCreate) createSpec() (*Guild, *sqlgraph.CreateSpec) {
Value: value,
Column: guild.FieldCreateTime,
})
gu.CreateTime = value
_node.CreateTime = value
}
if value, ok := gc.mutation.UpdateTime(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
@ -181,7 +196,7 @@ func (gc *GuildCreate) createSpec() (*Guild, *sqlgraph.CreateSpec) {
Value: value,
Column: guild.FieldUpdateTime,
})
gu.UpdateTime = value
_node.UpdateTime = value
}
if value, ok := gc.mutation.Snowflake(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
@ -189,7 +204,7 @@ func (gc *GuildCreate) createSpec() (*Guild, *sqlgraph.CreateSpec) {
Value: value,
Column: guild.FieldSnowflake,
})
gu.Snowflake = value
_node.Snowflake = value
}
if value, ok := gc.mutation.Message(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
@ -197,7 +212,7 @@ func (gc *GuildCreate) createSpec() (*Guild, *sqlgraph.CreateSpec) {
Value: value,
Column: guild.FieldMessage,
})
gu.Message = value
_node.Message = value
}
if value, ok := gc.mutation.Categories(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
@ -205,7 +220,7 @@ func (gc *GuildCreate) createSpec() (*Guild, *sqlgraph.CreateSpec) {
Value: value,
Column: guild.FieldCategories,
})
gu.Categories = value
_node.Categories = value
}
if value, ok := gc.mutation.Entitlements(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
@ -213,9 +228,9 @@ func (gc *GuildCreate) createSpec() (*Guild, *sqlgraph.CreateSpec) {
Value: value,
Column: guild.FieldEntitlements,
})
gu.Entitlements = value
_node.Entitlements = value
}
return gu, _spec
return _node, _spec
}
// GuildCreateBulk is the builder for creating a bulk of Guild entities.
@ -232,14 +247,15 @@ func (gcb *GuildCreateBulk) Save(ctx context.Context) ([]*Guild, error) {
for i := range gcb.builders {
func(i int, root context.Context) {
builder := gcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
if err := builder.preSave(); err != nil {
return nil, err
}
mutation, ok := m.(*GuildMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error

View file

@ -54,23 +54,23 @@ func (gq *GuildQuery) Order(o ...OrderFunc) *GuildQuery {
// First returns the first Guild entity in the query. Returns *NotFoundError when no guild was found.
func (gq *GuildQuery) First(ctx context.Context) (*Guild, error) {
gus, err := gq.Limit(1).All(ctx)
nodes, err := gq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(gus) == 0 {
if len(nodes) == 0 {
return nil, &NotFoundError{guild.Label}
}
return gus[0], nil
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (gq *GuildQuery) FirstX(ctx context.Context) *Guild {
gu, err := gq.First(ctx)
node, err := gq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return gu
return node
}
// FirstID returns the first Guild id in the query. Returns *NotFoundError when no id was found.
@ -97,13 +97,13 @@ func (gq *GuildQuery) FirstXID(ctx context.Context) int {
// Only returns the only Guild entity in the query, returns an error if not exactly one entity was returned.
func (gq *GuildQuery) Only(ctx context.Context) (*Guild, error) {
gus, err := gq.Limit(2).All(ctx)
nodes, err := gq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(gus) {
switch len(nodes) {
case 1:
return gus[0], nil
return nodes[0], nil
case 0:
return nil, &NotFoundError{guild.Label}
default:
@ -113,11 +113,11 @@ func (gq *GuildQuery) Only(ctx context.Context) (*Guild, error) {
// OnlyX is like Only, but panics if an error occurs.
func (gq *GuildQuery) OnlyX(ctx context.Context) *Guild {
gu, err := gq.Only(ctx)
node, err := gq.Only(ctx)
if err != nil {
panic(err)
}
return gu
return node
}
// OnlyID returns the only Guild id in the query, returns an error if not exactly one id was returned.
@ -156,11 +156,11 @@ func (gq *GuildQuery) All(ctx context.Context) ([]*Guild, error) {
// AllX is like All, but panics if an error occurs.
func (gq *GuildQuery) AllX(ctx context.Context) []*Guild {
gus, err := gq.All(ctx)
nodes, err := gq.All(ctx)
if err != nil {
panic(err)
}
return gus
return nodes
}
// IDs executes the query and returns a list of Guild ids.
@ -362,7 +362,7 @@ func (gq *GuildQuery) querySpec() *sqlgraph.QuerySpec {
if ps := gq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
ps[i](selector, guild.ValidColumn)
}
}
}
@ -381,7 +381,7 @@ func (gq *GuildQuery) sqlQuery() *sql.Selector {
p(selector)
}
for _, p := range gq.order {
p(selector)
p(selector, guild.ValidColumn)
}
if offset := gq.offset; offset != nil {
// limit is mandatory for offset clause. We start
@ -616,8 +616,17 @@ func (ggb *GuildGroupBy) BoolX(ctx context.Context) bool {
}
func (ggb *GuildGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range ggb.fields {
if !guild.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := ggb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := ggb.sqlQuery().Query()
query, args := selector.Query()
if err := ggb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
@ -630,7 +639,7 @@ func (ggb *GuildGroupBy) sqlQuery() *sql.Selector {
columns := make([]string, 0, len(ggb.fields)+len(ggb.fns))
columns = append(columns, ggb.fields...)
for _, fn := range ggb.fns {
columns = append(columns, fn(selector))
columns = append(columns, fn(selector, guild.ValidColumn))
}
return selector.Select(columns...).GroupBy(ggb.fields...)
}
@ -850,6 +859,11 @@ func (gs *GuildSelect) BoolX(ctx context.Context) bool {
}
func (gs *GuildSelect) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range gs.fields {
if !guild.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for selection", f)}
}
}
rows := &sql.Rows{}
query, args := gs.sqlQuery().Query()
if err := gs.driver.Query(ctx, query, args, rows); err != nil {

View file

@ -53,14 +53,11 @@ func (gu *GuildUpdate) Mutation() *GuildMutation {
// Save executes the query and returns the number of rows/vertices matched by this operation.
func (gu *GuildUpdate) Save(ctx context.Context) (int, error) {
if _, ok := gu.mutation.UpdateTime(); !ok {
v := guild.UpdateDefaultUpdateTime()
gu.mutation.SetUpdateTime(v)
}
var (
err error
affected int
)
gu.defaults()
if len(gu.hooks) == 0 {
affected, err = gu.sqlSave(ctx)
} else {
@ -106,6 +103,14 @@ func (gu *GuildUpdate) ExecX(ctx context.Context) {
}
}
// defaults sets the default values of the builder before save.
func (gu *GuildUpdate) defaults() {
if _, ok := gu.mutation.UpdateTime(); !ok {
v := guild.UpdateDefaultUpdateTime()
gu.mutation.SetUpdateTime(v)
}
}
func (gu *GuildUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
@ -195,14 +200,11 @@ func (guo *GuildUpdateOne) Mutation() *GuildMutation {
// Save executes the query and returns the updated entity.
func (guo *GuildUpdateOne) Save(ctx context.Context) (*Guild, error) {
if _, ok := guo.mutation.UpdateTime(); !ok {
v := guild.UpdateDefaultUpdateTime()
guo.mutation.SetUpdateTime(v)
}
var (
err error
node *Guild
)
guo.defaults()
if len(guo.hooks) == 0 {
node, err = guo.sqlSave(ctx)
} else {
@ -228,11 +230,11 @@ func (guo *GuildUpdateOne) Save(ctx context.Context) (*Guild, error) {
// SaveX is like Save, but panics if an error occurs.
func (guo *GuildUpdateOne) SaveX(ctx context.Context) *Guild {
gu, err := guo.Save(ctx)
node, err := guo.Save(ctx)
if err != nil {
panic(err)
}
return gu
return node
}
// Exec executes the query on the entity.
@ -248,7 +250,15 @@ func (guo *GuildUpdateOne) ExecX(ctx context.Context) {
}
}
func (guo *GuildUpdateOne) sqlSave(ctx context.Context) (gu *Guild, err error) {
// defaults sets the default values of the builder before save.
func (guo *GuildUpdateOne) defaults() {
if _, ok := guo.mutation.UpdateTime(); !ok {
v := guild.UpdateDefaultUpdateTime()
guo.mutation.SetUpdateTime(v)
}
}
func (guo *GuildUpdateOne) sqlSave(ctx context.Context) (_node *Guild, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: guild.Table,
@ -292,9 +302,9 @@ func (guo *GuildUpdateOne) sqlSave(ctx context.Context) (gu *Guild, err error) {
Column: guild.FieldEntitlements,
})
}
gu = &Guild{config: guo.config}
_spec.Assign = gu.assignValues
_spec.ScanValues = gu.scanValues()
_node = &Guild{config: guo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues()
if err = sqlgraph.UpdateNode(ctx, guo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{guild.Label}
@ -303,5 +313,5 @@ func (guo *GuildUpdateOne) sqlSave(ctx context.Context) (gu *Guild, err error) {
}
return nil, err
}
return gu, nil
return _node, nil
}

View file

@ -142,7 +142,7 @@ func HasFields(field string, fields ...string) Condition {
// If executes the given hook under condition.
//
// Hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
//
func If(hk ent.Hook, cond Condition) ent.Hook {
return func(next ent.Mutator) ent.Mutator {

View file

@ -29,7 +29,7 @@ var (
// flexibility in the schema changes.
WithDropIndex = schema.WithDropIndex
// WithFixture sets the foreign-key renaming option to the migration when upgrading
// ent from v0.1.0 (issue-#285). Defaults to true.
// ent from v0.1.0 (issue-#285). Defaults to false.
WithFixture = schema.WithFixture
)

View file

@ -5,6 +5,6 @@ package runtime
// The schema-stitching logic is generated in github.com/roleypoly/roleypoly/src/db/ent/runtime.go
const (
Version = "v0.4.2" // Version of ent codegen.
Sum = "h1:JzU5dYJH9XdjfIKgOiPPK3szkqLqcdPWgVder4Ogows=" // Sum of ent codegen.
Version = "v0.4.3" // Version of ent codegen.
Sum = "h1:ds9HENceKzpGBgCRlkZNq6TqBIegwKcF3e5reuV9Z0M=" // Sum of ent codegen.
)

View file

@ -40,6 +40,16 @@ var Columns = []string{
FieldExpiresAt,
}
// 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 (
// DefaultCreateTime holds the default value on creation for the create_time field.
DefaultCreateTime func() time.Time

View file

@ -87,14 +87,15 @@ func (sc *SessionCreate) Mutation() *SessionMutation {
// Save creates the Session in the database.
func (sc *SessionCreate) Save(ctx context.Context) (*Session, error) {
if err := sc.preSave(); err != nil {
return nil, err
}
var (
err error
node *Session
)
sc.defaults()
if len(sc.hooks) == 0 {
if err = sc.check(); err != nil {
return nil, err
}
node, err = sc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
@ -102,6 +103,9 @@ func (sc *SessionCreate) Save(ctx context.Context) (*Session, error) {
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = sc.check(); err != nil {
return nil, err
}
sc.mutation = mutation
node, err = sc.sqlSave(ctx)
mutation.done = true
@ -126,7 +130,8 @@ func (sc *SessionCreate) SaveX(ctx context.Context) *Session {
return v
}
func (sc *SessionCreate) preSave() error {
// defaults sets the default values of the builder before save.
func (sc *SessionCreate) defaults() {
if _, ok := sc.mutation.CreateTime(); !ok {
v := session.DefaultCreateTime()
sc.mutation.SetCreateTime(v)
@ -135,6 +140,20 @@ func (sc *SessionCreate) preSave() error {
v := session.DefaultUpdateTime()
sc.mutation.SetUpdateTime(v)
}
if _, ok := sc.mutation.ExpiresAt(); !ok {
v := session.DefaultExpiresAt()
sc.mutation.SetExpiresAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (sc *SessionCreate) check() error {
if _, ok := sc.mutation.CreateTime(); !ok {
return &ValidationError{Name: "create_time", err: errors.New("ent: missing required field \"create_time\"")}
}
if _, ok := sc.mutation.UpdateTime(); !ok {
return &ValidationError{Name: "update_time", err: errors.New("ent: missing required field \"update_time\"")}
}
if _, ok := sc.mutation.SessionID(); !ok {
return &ValidationError{Name: "session_id", err: errors.New("ent: missing required field \"session_id\"")}
}
@ -150,14 +169,13 @@ func (sc *SessionCreate) preSave() error {
}
}
if _, ok := sc.mutation.ExpiresAt(); !ok {
v := session.DefaultExpiresAt()
sc.mutation.SetExpiresAt(v)
return &ValidationError{Name: "expires_at", err: errors.New("ent: missing required field \"expires_at\"")}
}
return nil
}
func (sc *SessionCreate) sqlSave(ctx context.Context) (*Session, error) {
s, _spec := sc.createSpec()
_node, _spec := sc.createSpec()
if err := sqlgraph.CreateNode(ctx, sc.driver, _spec); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
@ -165,13 +183,13 @@ func (sc *SessionCreate) sqlSave(ctx context.Context) (*Session, error) {
return nil, err
}
id := _spec.ID.Value.(int64)
s.ID = int(id)
return s, nil
_node.ID = int(id)
return _node, nil
}
func (sc *SessionCreate) createSpec() (*Session, *sqlgraph.CreateSpec) {
var (
s = &Session{config: sc.config}
_node = &Session{config: sc.config}
_spec = &sqlgraph.CreateSpec{
Table: session.Table,
ID: &sqlgraph.FieldSpec{
@ -186,7 +204,7 @@ func (sc *SessionCreate) createSpec() (*Session, *sqlgraph.CreateSpec) {
Value: value,
Column: session.FieldCreateTime,
})
s.CreateTime = value
_node.CreateTime = value
}
if value, ok := sc.mutation.UpdateTime(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
@ -194,7 +212,7 @@ func (sc *SessionCreate) createSpec() (*Session, *sqlgraph.CreateSpec) {
Value: value,
Column: session.FieldUpdateTime,
})
s.UpdateTime = value
_node.UpdateTime = value
}
if value, ok := sc.mutation.SessionID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
@ -202,7 +220,7 @@ func (sc *SessionCreate) createSpec() (*Session, *sqlgraph.CreateSpec) {
Value: value,
Column: session.FieldSessionID,
})
s.SessionID = value
_node.SessionID = value
}
if value, ok := sc.mutation.UserID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
@ -210,7 +228,7 @@ func (sc *SessionCreate) createSpec() (*Session, *sqlgraph.CreateSpec) {
Value: value,
Column: session.FieldUserID,
})
s.UserID = value
_node.UserID = value
}
if value, ok := sc.mutation.Source(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
@ -218,7 +236,7 @@ func (sc *SessionCreate) createSpec() (*Session, *sqlgraph.CreateSpec) {
Value: value,
Column: session.FieldSource,
})
s.Source = value
_node.Source = value
}
if value, ok := sc.mutation.ExpiresAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
@ -226,9 +244,9 @@ func (sc *SessionCreate) createSpec() (*Session, *sqlgraph.CreateSpec) {
Value: value,
Column: session.FieldExpiresAt,
})
s.ExpiresAt = value
_node.ExpiresAt = value
}
return s, _spec
return _node, _spec
}
// SessionCreateBulk is the builder for creating a bulk of Session entities.
@ -245,14 +263,15 @@ func (scb *SessionCreateBulk) Save(ctx context.Context) ([]*Session, error) {
for i := range scb.builders {
func(i int, root context.Context) {
builder := scb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
if err := builder.preSave(); err != nil {
return nil, err
}
mutation, ok := m.(*SessionMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error

View file

@ -54,23 +54,23 @@ func (sq *SessionQuery) Order(o ...OrderFunc) *SessionQuery {
// First returns the first Session entity in the query. Returns *NotFoundError when no session was found.
func (sq *SessionQuery) First(ctx context.Context) (*Session, error) {
sSlice, err := sq.Limit(1).All(ctx)
nodes, err := sq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(sSlice) == 0 {
if len(nodes) == 0 {
return nil, &NotFoundError{session.Label}
}
return sSlice[0], nil
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (sq *SessionQuery) FirstX(ctx context.Context) *Session {
s, err := sq.First(ctx)
node, err := sq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return s
return node
}
// FirstID returns the first Session id in the query. Returns *NotFoundError when no id was found.
@ -97,13 +97,13 @@ func (sq *SessionQuery) FirstXID(ctx context.Context) int {
// Only returns the only Session entity in the query, returns an error if not exactly one entity was returned.
func (sq *SessionQuery) Only(ctx context.Context) (*Session, error) {
sSlice, err := sq.Limit(2).All(ctx)
nodes, err := sq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(sSlice) {
switch len(nodes) {
case 1:
return sSlice[0], nil
return nodes[0], nil
case 0:
return nil, &NotFoundError{session.Label}
default:
@ -113,11 +113,11 @@ func (sq *SessionQuery) Only(ctx context.Context) (*Session, error) {
// OnlyX is like Only, but panics if an error occurs.
func (sq *SessionQuery) OnlyX(ctx context.Context) *Session {
s, err := sq.Only(ctx)
node, err := sq.Only(ctx)
if err != nil {
panic(err)
}
return s
return node
}
// OnlyID returns the only Session id in the query, returns an error if not exactly one id was returned.
@ -156,11 +156,11 @@ func (sq *SessionQuery) All(ctx context.Context) ([]*Session, error) {
// AllX is like All, but panics if an error occurs.
func (sq *SessionQuery) AllX(ctx context.Context) []*Session {
sSlice, err := sq.All(ctx)
nodes, err := sq.All(ctx)
if err != nil {
panic(err)
}
return sSlice
return nodes
}
// IDs executes the query and returns a list of Session ids.
@ -362,7 +362,7 @@ func (sq *SessionQuery) querySpec() *sqlgraph.QuerySpec {
if ps := sq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
ps[i](selector, session.ValidColumn)
}
}
}
@ -381,7 +381,7 @@ func (sq *SessionQuery) sqlQuery() *sql.Selector {
p(selector)
}
for _, p := range sq.order {
p(selector)
p(selector, session.ValidColumn)
}
if offset := sq.offset; offset != nil {
// limit is mandatory for offset clause. We start
@ -616,8 +616,17 @@ func (sgb *SessionGroupBy) BoolX(ctx context.Context) bool {
}
func (sgb *SessionGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range sgb.fields {
if !session.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := sgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := sgb.sqlQuery().Query()
query, args := selector.Query()
if err := sgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
@ -630,7 +639,7 @@ func (sgb *SessionGroupBy) sqlQuery() *sql.Selector {
columns := make([]string, 0, len(sgb.fields)+len(sgb.fns))
columns = append(columns, sgb.fields...)
for _, fn := range sgb.fns {
columns = append(columns, fn(selector))
columns = append(columns, fn(selector, session.ValidColumn))
}
return selector.Select(columns...).GroupBy(sgb.fields...)
}
@ -850,6 +859,11 @@ func (ss *SessionSelect) BoolX(ctx context.Context) bool {
}
func (ss *SessionSelect) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range ss.fields {
if !session.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for selection", f)}
}
}
rows := &sql.Rows{}
query, args := ss.sqlQuery().Query()
if err := ss.driver.Query(ctx, query, args, rows); err != nil {

View file

@ -34,14 +34,11 @@ func (su *SessionUpdate) Mutation() *SessionMutation {
// Save executes the query and returns the number of rows/vertices matched by this operation.
func (su *SessionUpdate) Save(ctx context.Context) (int, error) {
if _, ok := su.mutation.UpdateTime(); !ok {
v := session.UpdateDefaultUpdateTime()
su.mutation.SetUpdateTime(v)
}
var (
err error
affected int
)
su.defaults()
if len(su.hooks) == 0 {
affected, err = su.sqlSave(ctx)
} else {
@ -87,6 +84,14 @@ func (su *SessionUpdate) ExecX(ctx context.Context) {
}
}
// defaults sets the default values of the builder before save.
func (su *SessionUpdate) defaults() {
if _, ok := su.mutation.UpdateTime(); !ok {
v := session.UpdateDefaultUpdateTime()
su.mutation.SetUpdateTime(v)
}
}
func (su *SessionUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
@ -137,14 +142,11 @@ func (suo *SessionUpdateOne) Mutation() *SessionMutation {
// Save executes the query and returns the updated entity.
func (suo *SessionUpdateOne) Save(ctx context.Context) (*Session, error) {
if _, ok := suo.mutation.UpdateTime(); !ok {
v := session.UpdateDefaultUpdateTime()
suo.mutation.SetUpdateTime(v)
}
var (
err error
node *Session
)
suo.defaults()
if len(suo.hooks) == 0 {
node, err = suo.sqlSave(ctx)
} else {
@ -170,11 +172,11 @@ func (suo *SessionUpdateOne) Save(ctx context.Context) (*Session, error) {
// SaveX is like Save, but panics if an error occurs.
func (suo *SessionUpdateOne) SaveX(ctx context.Context) *Session {
s, err := suo.Save(ctx)
node, err := suo.Save(ctx)
if err != nil {
panic(err)
}
return s
return node
}
// Exec executes the query on the entity.
@ -190,7 +192,15 @@ func (suo *SessionUpdateOne) ExecX(ctx context.Context) {
}
}
func (suo *SessionUpdateOne) sqlSave(ctx context.Context) (s *Session, err error) {
// defaults sets the default values of the builder before save.
func (suo *SessionUpdateOne) defaults() {
if _, ok := suo.mutation.UpdateTime(); !ok {
v := session.UpdateDefaultUpdateTime()
suo.mutation.SetUpdateTime(v)
}
}
func (suo *SessionUpdateOne) sqlSave(ctx context.Context) (_node *Session, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: session.Table,
@ -213,9 +223,9 @@ func (suo *SessionUpdateOne) sqlSave(ctx context.Context) (s *Session, err error
Column: session.FieldUpdateTime,
})
}
s = &Session{config: suo.config}
_spec.Assign = s.assignValues
_spec.ScanValues = s.scanValues()
_node = &Session{config: suo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues()
if err = sqlgraph.UpdateNode(ctx, suo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{session.Label}
@ -224,5 +234,5 @@ func (suo *SessionUpdateOne) sqlSave(ctx context.Context) (s *Session, err error
}
return nil, err
}
return s, nil
return _node, nil
}