entc: abandon plugins

Summary:
Go plugin is not a good solution for both internal and external usage.
It's hard to manage and maintain matching versions (both Go and external libraries), and it does not support Windows.

Reviewed By: alexsn

Differential Revision: D16582217

fbshipit-source-id: 81876d2c6f30bbfc16ecf9e5000f0670f2e62484
This commit is contained in:
Ariel Mashraki
2019-08-01 05:02:46 -07:00
committed by Facebook Github Bot
parent 8cb2428ea3
commit 2c8b5a65b7
54 changed files with 915 additions and 2909 deletions

View File

@@ -29,6 +29,8 @@ var Columns = []string{
var (
fields = schema.File{}.Fields()
// DefaultSize holds the default value for the size field.
DefaultSize = fields[0].Value().(int)
// SizeValidator is a validator for the "size" field. It is called by the builders before save.
SizeValidator = fields[0].Validators()[0].(func(int) error)
)

View File

@@ -30,6 +30,14 @@ func (fc *FileCreate) SetSize(i int) *FileCreate {
return fc
}
// SetNillableSize sets the size field if the given value is not nil.
func (fc *FileCreate) SetNillableSize(i *int) *FileCreate {
if i != nil {
fc.SetSize(*i)
}
return fc
}
// SetName sets the name field.
func (fc *FileCreate) SetName(s string) *FileCreate {
fc.name = &s
@@ -39,7 +47,8 @@ func (fc *FileCreate) SetName(s string) *FileCreate {
// Save creates the File in the database.
func (fc *FileCreate) Save(ctx context.Context) (*File, error) {
if fc.size == nil {
return nil, errors.New("ent: missing required field \"size\"")
v := file.DefaultSize
fc.size = &v
}
if err := file.SizeValidator(*fc.size); err != nil {
return nil, fmt.Errorf("ent: validator failed for field \"size\": %v", err)

View File

@@ -37,6 +37,14 @@ func (fu *FileUpdate) SetSize(i int) *FileUpdate {
return fu
}
// SetNillableSize sets the size field if the given value is not nil.
func (fu *FileUpdate) SetNillableSize(i *int) *FileUpdate {
if i != nil {
fu.SetSize(*i)
}
return fu
}
// SetName sets the name field.
func (fu *FileUpdate) SetName(s string) *FileUpdate {
fu.name = &s
@@ -179,6 +187,14 @@ func (fuo *FileUpdateOne) SetSize(i int) *FileUpdateOne {
return fuo
}
// SetNillableSize sets the size field if the given value is not nil.
func (fuo *FileUpdateOne) SetNillableSize(i *int) *FileUpdateOne {
if i != nil {
fuo.SetSize(*i)
}
return fuo
}
// SetName sets the name field.
func (fuo *FileUpdateOne) SetName(s string) *FileUpdateOne {
fuo.name = &s

View File

@@ -13,16 +13,12 @@ const (
FieldID = "id"
// FieldActive holds the string denoting the active vertex property in the database.
FieldActive = "active"
// DefaultActive holds the default value for the active field.
DefaultActive = true
// FieldExpire holds the string denoting the expire vertex property in the database.
FieldExpire = "expire"
// FieldType holds the string denoting the type vertex property in the database.
FieldType = "type"
// FieldMaxUsers holds the string denoting the max_users vertex property in the database.
FieldMaxUsers = "max_users"
// DefaultMaxUsers holds the default value for the max_users field.
DefaultMaxUsers int = 10
// FieldName holds the string denoting the name vertex property in the database.
FieldName = "name"
@@ -83,8 +79,12 @@ var (
var (
fields = schema.Group{}.Fields()
// DefaultActive holds the default value for the active field.
DefaultActive = fields[0].Value().(bool)
// TypeValidator is a validator for the "type" field. It is called by the builders before save.
TypeValidator = fields[2].Validators()[0].(func(string) error)
// DefaultMaxUsers holds the default value for the max_users field.
DefaultMaxUsers = fields[3].Value().(int)
// MaxUsersValidator is a validator for the "max_users" field. It is called by the builders before save.
MaxUsersValidator = fields[3].Validators()[0].(func(int) error)
// NameValidator is a validator for the "name" field. It is called by the builders before save.

View File

@@ -2,6 +2,10 @@
package groupinfo
import (
"fbc/ent/entc/integration/ent/schema"
)
const (
// Label holds the string label denoting the groupinfo type in the database.
Label = "group_info"
@@ -11,8 +15,6 @@ const (
FieldDesc = "desc"
// FieldMaxUsers holds the string denoting the max_users vertex property in the database.
FieldMaxUsers = "max_users"
// DefaultMaxUsers holds the default value for the max_users field.
DefaultMaxUsers int = 10000
// Table holds the table name of the groupinfo in the database.
Table = "group_infos"
@@ -34,3 +36,9 @@ var Columns = []string{
FieldDesc,
FieldMaxUsers,
}
var (
fields = schema.GroupInfo{}.Fields()
// DefaultMaxUsers holds the default value for the max_users field.
DefaultMaxUsers = fields[1].Value().(int)
)

View File

@@ -1,6 +1,8 @@
package schema
import (
"math"
"fbc/ent"
"fbc/ent/field"
)
@@ -14,6 +16,7 @@ type File struct {
func (File) Fields() []ent.Field {
return []ent.Field{
field.Int("size").
Default(math.MaxInt32).
Positive(),
field.String("name"),
}

View File

@@ -2,6 +2,10 @@
package user
import (
"fbc/ent/entc/integration/ent/schema"
)
const (
// Label holds the string label denoting the user type in the database.
Label = "user"
@@ -13,8 +17,6 @@ const (
FieldName = "name"
// FieldLast holds the string denoting the last vertex property in the database.
FieldLast = "last"
// DefaultLast holds the default value for the last field.
DefaultLast = "unknown"
// FieldNickname holds the string denoting the nickname vertex property in the database.
FieldNickname = "nickname"
// FieldPhone holds the string denoting the phone vertex property in the database.
@@ -122,3 +124,9 @@ var (
// primary key for the following relation (M2M).
FollowingPrimaryKey = []string{"user_id", "follower_id"}
)
var (
fields = schema.User{}.Fields()
// DefaultLast holds the default value for the last field.
DefaultLast = fields[2].Value().(string)
)

View File

@@ -1,6 +1,5 @@
package integration
//go:generate go run ../cmd/entc/entc.go generate --storage=sql,gremlin ./ent/schema
//go:generate go run ../cmd/entc/entc.go generate --storage=sql,gremlin ./plugin/ent/schema
//go:generate go run ../cmd/entc/entc.go generate ./migrate/entv1/schema
//go:generate go run ../cmd/entc/entc.go generate ./migrate/entv2/schema

View File

@@ -1,8 +0,0 @@
### Example plugins for testing purpose
#### Generating new assets for plugin tests
From `plugin` directory, run:
```
go run ../../cmd/entc/entc.go generate ./ent/schema
```

View File

@@ -1,124 +0,0 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"bytes"
"fmt"
"strconv"
"fbc/ent/dialect/gremlin"
"fbc/ent/dialect/sql"
)
// Boring is the model entity for the Boring schema.
type Boring struct {
config
// ID of the ent.
ID string `json:"id,omitempty"`
}
// FromRows scans the sql response data into Boring.
func (b *Boring) FromRows(rows *sql.Rows) error {
var vb struct {
ID int
}
// the order here should be the same as in the `boring.Columns`.
if err := rows.Scan(
&vb.ID,
); err != nil {
return err
}
b.ID = strconv.Itoa(vb.ID)
return nil
}
// FromResponse scans the gremlin response data into Boring.
func (b *Boring) FromResponse(res *gremlin.Response) error {
vmap, err := res.ReadValueMap()
if err != nil {
return err
}
var vb struct {
ID string `json:"id,omitempty"`
}
if err := vmap.Decode(&vb); err != nil {
return err
}
b.ID = vb.ID
return nil
}
// Update returns a builder for updating this Boring.
// Note that, you need to call Boring.Unwrap() before calling this method, if this Boring
// was returned from a transaction, and the transaction was committed or rolled back.
func (b *Boring) Update() *BoringUpdateOne {
return (&BoringClient{b.config}).UpdateOne(b)
}
// Unwrap unwraps the entity that was returned from a transaction after it was closed,
// so that all next queries will be executed through the driver which created the transaction.
func (b *Boring) Unwrap() *Boring {
tx, ok := b.config.driver.(*txDriver)
if !ok {
panic("ent: Boring is not a transactional entity")
}
b.config.driver = tx.drv
return b
}
// String implements the fmt.Stringer.
func (b *Boring) String() string {
buf := bytes.NewBuffer(nil)
buf.WriteString("Boring(")
buf.WriteString(fmt.Sprintf("id=%v", b.ID))
buf.WriteString(")")
return buf.String()
}
// id returns the int representation of the ID field.
func (b *Boring) id() int {
id, _ := strconv.Atoi(b.ID)
return id
}
// Borings is a parsable slice of Boring.
type Borings []*Boring
// FromRows scans the sql response data into Borings.
func (b *Borings) FromRows(rows *sql.Rows) error {
for rows.Next() {
vb := &Boring{}
if err := vb.FromRows(rows); err != nil {
return err
}
*b = append(*b, vb)
}
return nil
}
// FromResponse scans the gremlin response data into Borings.
func (b *Borings) FromResponse(res *gremlin.Response) error {
vmap, err := res.ReadValueMap()
if err != nil {
return err
}
var vb []struct {
ID string `json:"id,omitempty"`
}
if err := vmap.Decode(&vb); err != nil {
return err
}
for _, v := range vb {
*b = append(*b, &Boring{
ID: v.ID,
})
}
return nil
}
func (b Borings) config(cfg config) {
for i := range b {
b[i].config = cfg
}
}

View File

@@ -1,18 +0,0 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package boring
const (
// Label holds the string label denoting the boring type in the database.
Label = "boring"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// Table holds the table name of the boring in the database.
Table = "borings"
)
// Columns holds all SQL columns are boring fields.
var Columns = []string{
FieldID,
}

View File

@@ -1,194 +0,0 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package boring
import (
"strconv"
"fbc/ent/entc/integration/plugin/ent/predicate"
"fbc/ent/dialect/gremlin/graph/dsl"
"fbc/ent/dialect/gremlin/graph/dsl/__"
"fbc/ent/dialect/gremlin/graph/dsl/p"
"fbc/ent/dialect/sql"
)
// ID filters vertices based on their identifier.
func ID(id string) predicate.Boring {
return predicate.BoringPerDialect(
func(s *sql.Selector) {
id, _ := strconv.Atoi(id)
s.Where(sql.EQ(s.C(FieldID), id))
},
func(t *dsl.Traversal) {
t.HasID(id)
},
)
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id string) predicate.Boring {
return predicate.BoringPerDialect(
func(s *sql.Selector) {
v, _ := strconv.Atoi(id)
s.Where(sql.EQ(s.C(FieldID), v))
},
func(t *dsl.Traversal) {
t.HasID(p.EQ(id))
},
)
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id string) predicate.Boring {
return predicate.BoringPerDialect(
func(s *sql.Selector) {
v, _ := strconv.Atoi(id)
s.Where(sql.NEQ(s.C(FieldID), v))
},
func(t *dsl.Traversal) {
t.HasID(p.NEQ(id))
},
)
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id string) predicate.Boring {
return predicate.BoringPerDialect(
func(s *sql.Selector) {
v, _ := strconv.Atoi(id)
s.Where(sql.GT(s.C(FieldID), v))
},
func(t *dsl.Traversal) {
t.HasID(p.GT(id))
},
)
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id string) predicate.Boring {
return predicate.BoringPerDialect(
func(s *sql.Selector) {
v, _ := strconv.Atoi(id)
s.Where(sql.GTE(s.C(FieldID), v))
},
func(t *dsl.Traversal) {
t.HasID(p.GTE(id))
},
)
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id string) predicate.Boring {
return predicate.BoringPerDialect(
func(s *sql.Selector) {
v, _ := strconv.Atoi(id)
s.Where(sql.LT(s.C(FieldID), v))
},
func(t *dsl.Traversal) {
t.HasID(p.LT(id))
},
)
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id string) predicate.Boring {
return predicate.BoringPerDialect(
func(s *sql.Selector) {
v, _ := strconv.Atoi(id)
s.Where(sql.LTE(s.C(FieldID), v))
},
func(t *dsl.Traversal) {
t.HasID(p.LTE(id))
},
)
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...string) predicate.Boring {
return predicate.BoringPerDialect(
func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i], _ = strconv.Atoi(ids[i])
}
s.Where(sql.In(s.C(FieldID), v...))
},
func(t *dsl.Traversal) {
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
t.HasID(p.Within(v...))
},
)
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...string) predicate.Boring {
return predicate.BoringPerDialect(
func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i], _ = strconv.Atoi(ids[i])
}
s.Where(sql.NotIn(s.C(FieldID), v...))
},
func(t *dsl.Traversal) {
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
t.HasID(p.Without(v...))
},
)
}
// Or groups list of predicates with the or operator between them.
func Or(predicates ...predicate.Boring) predicate.Boring {
return predicate.BoringPerDialect(
func(s *sql.Selector) {
for i, p := range predicates {
if i > 0 {
s.Or()
}
p(s)
}
},
func(tr *dsl.Traversal) {
trs := make([]interface{}, 0, len(predicates))
for _, p := range predicates {
t := __.New()
p(t)
trs = append(trs, t)
}
tr.Where(__.Or(trs...))
},
)
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Boring) predicate.Boring {
return predicate.BoringPerDialect(
func(s *sql.Selector) {
p(s.Not())
},
func(tr *dsl.Traversal) {
t := __.New()
p(t)
tr.Where(__.Not(t))
},
)
}

View File

@@ -1,89 +0,0 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"strconv"
"fbc/ent/entc/integration/plugin/ent/boring"
"fbc/ent/dialect"
"fbc/ent/dialect/gremlin"
"fbc/ent/dialect/gremlin/graph/dsl"
"fbc/ent/dialect/gremlin/graph/dsl/g"
"fbc/ent/dialect/sql"
)
// BoringCreate is the builder for creating a Boring entity.
type BoringCreate struct {
config
}
// Save creates the Boring in the database.
func (bc *BoringCreate) Save(ctx context.Context) (*Boring, error) {
switch bc.driver.Dialect() {
case dialect.MySQL, dialect.SQLite:
return bc.sqlSave(ctx)
case dialect.Neptune:
return bc.gremlinSave(ctx)
default:
return nil, errors.New("ent: unsupported dialect")
}
}
// SaveX calls Save and panics if Save returns an error.
func (bc *BoringCreate) SaveX(ctx context.Context) *Boring {
v, err := bc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
func (bc *BoringCreate) sqlSave(ctx context.Context) (*Boring, error) {
var (
res sql.Result
b = &Boring{config: bc.config}
)
tx, err := bc.driver.Tx(ctx)
if err != nil {
return nil, err
}
builder := sql.Insert(boring.Table).Default(bc.driver.Dialect())
query, args := builder.Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
id, err := res.LastInsertId()
if err != nil {
return nil, rollback(tx, err)
}
b.ID = strconv.FormatInt(id, 10)
if err := tx.Commit(); err != nil {
return nil, err
}
return b, nil
}
func (bc *BoringCreate) gremlinSave(ctx context.Context) (*Boring, error) {
res := &gremlin.Response{}
query, bindings := bc.gremlin().Query()
if err := bc.driver.Exec(ctx, query, bindings, res); err != nil {
return nil, err
}
if err, ok := isConstantError(res); ok {
return nil, err
}
b := &Boring{config: bc.config}
if err := b.FromResponse(res); err != nil {
return nil, err
}
return b, nil
}
func (bc *BoringCreate) gremlin() *dsl.Traversal {
v := g.AddV(boring.Label)
return v.ValueMap(true)
}

View File

@@ -1,87 +0,0 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fbc/ent/entc/integration/plugin/ent/boring"
"fbc/ent/entc/integration/plugin/ent/predicate"
"fbc/ent/dialect"
"fbc/ent/dialect/gremlin"
"fbc/ent/dialect/gremlin/graph/dsl"
"fbc/ent/dialect/gremlin/graph/dsl/g"
"fbc/ent/dialect/sql"
)
// BoringDelete is the builder for deleting a Boring entity.
type BoringDelete struct {
config
predicates []predicate.Boring
}
// Where adds a new predicate for the builder.
func (bd *BoringDelete) Where(ps ...predicate.Boring) *BoringDelete {
bd.predicates = append(bd.predicates, ps...)
return bd
}
// Exec executes the deletion query.
func (bd *BoringDelete) Exec(ctx context.Context) error {
switch bd.driver.Dialect() {
case dialect.MySQL, dialect.SQLite:
return bd.sqlExec(ctx)
case dialect.Neptune:
return bd.gremlinExec(ctx)
default:
return errors.New("ent: unsupported dialect")
}
}
// ExecX is like Exec, but panics if an error occurs.
func (bd *BoringDelete) ExecX(ctx context.Context) {
if err := bd.Exec(ctx); err != nil {
panic(err)
}
}
func (bd *BoringDelete) sqlExec(ctx context.Context) error {
var res sql.Result
selector := sql.Select().From(sql.Table(boring.Table))
for _, p := range bd.predicates {
p(selector)
}
query, args := sql.Delete(boring.Table).FromSelect(selector).Query()
return bd.driver.Exec(ctx, query, args, &res)
}
func (bd *BoringDelete) gremlinExec(ctx context.Context) error {
res := &gremlin.Response{}
query, bindings := bd.gremlin().Query()
return bd.driver.Exec(ctx, query, bindings, res)
}
func (bd *BoringDelete) gremlin() *dsl.Traversal {
t := g.V().HasLabel(boring.Label)
for _, p := range bd.predicates {
p(t)
}
return t.Drop()
}
// BoringDeleteOne is the builder for deleting a single Boring entity.
type BoringDeleteOne struct {
bd *BoringDelete
}
// Exec executes the deletion query.
func (bdo *BoringDeleteOne) Exec(ctx context.Context) error {
return bdo.bd.Exec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (bdo *BoringDeleteOne) ExecX(ctx context.Context) {
bdo.bd.ExecX(ctx)
}

View File

@@ -1,618 +0,0 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"math"
"fbc/ent/entc/integration/plugin/ent/boring"
"fbc/ent/entc/integration/plugin/ent/predicate"
"fbc/ent/dialect"
"fbc/ent/dialect/gremlin"
"fbc/ent/dialect/gremlin/graph/dsl"
"fbc/ent/dialect/gremlin/graph/dsl/__"
"fbc/ent/dialect/gremlin/graph/dsl/g"
"fbc/ent/dialect/sql"
)
// BoringQuery is the builder for querying Boring entities.
type BoringQuery struct {
config
limit *int
offset *int
order []Order
unique []string
predicates []predicate.Boring
// intermediate queries.
sql *sql.Selector
gremlin *dsl.Traversal
}
// Where adds a new predicate for the builder.
func (bq *BoringQuery) Where(ps ...predicate.Boring) *BoringQuery {
bq.predicates = append(bq.predicates, ps...)
return bq
}
// Limit adds a limit step to the query.
func (bq *BoringQuery) Limit(limit int) *BoringQuery {
bq.limit = &limit
return bq
}
// Offset adds an offset step to the query.
func (bq *BoringQuery) Offset(offset int) *BoringQuery {
bq.offset = &offset
return bq
}
// Order adds an order step to the query.
func (bq *BoringQuery) Order(o ...Order) *BoringQuery {
bq.order = append(bq.order, o...)
return bq
}
// Get returns a Boring entity by its id.
func (bq *BoringQuery) Get(ctx context.Context, id string) (*Boring, error) {
return bq.Where(boring.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (bq *BoringQuery) GetX(ctx context.Context, id string) *Boring {
b, err := bq.Get(ctx, id)
if err != nil {
panic(err)
}
return b
}
// First returns the first Boring entity in the query. Returns *ErrNotFound when no boring was found.
func (bq *BoringQuery) First(ctx context.Context) (*Boring, error) {
bs, err := bq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(bs) == 0 {
return nil, &ErrNotFound{boring.Label}
}
return bs[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (bq *BoringQuery) FirstX(ctx context.Context) *Boring {
b, err := bq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return b
}
// FirstID returns the first Boring id in the query. Returns *ErrNotFound when no id was found.
func (bq *BoringQuery) FirstID(ctx context.Context) (id string, err error) {
var ids []string
if ids, err = bq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &ErrNotFound{boring.Label}
return
}
return ids[0], nil
}
// FirstXID is like FirstID, but panics if an error occurs.
func (bq *BoringQuery) FirstXID(ctx context.Context) string {
id, err := bq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns the only Boring entity in the query, returns an error if not exactly one entity was returned.
func (bq *BoringQuery) Only(ctx context.Context) (*Boring, error) {
bs, err := bq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(bs) {
case 1:
return bs[0], nil
case 0:
return nil, &ErrNotFound{boring.Label}
default:
return nil, &ErrNotSingular{boring.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (bq *BoringQuery) OnlyX(ctx context.Context) *Boring {
b, err := bq.Only(ctx)
if err != nil {
panic(err)
}
return b
}
// OnlyID returns the only Boring id in the query, returns an error if not exactly one id was returned.
func (bq *BoringQuery) OnlyID(ctx context.Context) (id string, err error) {
var ids []string
if ids, err = bq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &ErrNotFound{boring.Label}
default:
err = &ErrNotSingular{boring.Label}
}
return
}
// OnlyXID is like OnlyID, but panics if an error occurs.
func (bq *BoringQuery) OnlyXID(ctx context.Context) string {
id, err := bq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Borings.
func (bq *BoringQuery) All(ctx context.Context) ([]*Boring, error) {
switch bq.driver.Dialect() {
case dialect.MySQL, dialect.SQLite:
return bq.sqlAll(ctx)
case dialect.Neptune:
return bq.gremlinAll(ctx)
default:
return nil, errors.New("ent: unsupported dialect")
}
}
// AllX is like All, but panics if an error occurs.
func (bq *BoringQuery) AllX(ctx context.Context) []*Boring {
bs, err := bq.All(ctx)
if err != nil {
panic(err)
}
return bs
}
// IDs executes the query and returns a list of Boring ids.
func (bq *BoringQuery) IDs(ctx context.Context) ([]string, error) {
switch bq.driver.Dialect() {
case dialect.MySQL, dialect.SQLite:
return bq.sqlIDs(ctx)
case dialect.Neptune:
return bq.gremlinIDs(ctx)
default:
return nil, errors.New("ent: unsupported dialect")
}
}
// IDsX is like IDs, but panics if an error occurs.
func (bq *BoringQuery) IDsX(ctx context.Context) []string {
ids, err := bq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (bq *BoringQuery) Count(ctx context.Context) (int, error) {
switch bq.driver.Dialect() {
case dialect.MySQL, dialect.SQLite:
return bq.sqlCount(ctx)
case dialect.Neptune:
return bq.gremlinCount(ctx)
default:
return 0, errors.New("ent: unsupported dialect")
}
}
// CountX is like Count, but panics if an error occurs.
func (bq *BoringQuery) CountX(ctx context.Context) int {
count, err := bq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (bq *BoringQuery) Exist(ctx context.Context) (bool, error) {
switch bq.driver.Dialect() {
case dialect.MySQL, dialect.SQLite:
return bq.sqlExist(ctx)
case dialect.Neptune:
return bq.gremlinExist(ctx)
default:
return false, errors.New("ent: unsupported dialect")
}
}
// ExistX is like Exist, but panics if an error occurs.
func (bq *BoringQuery) ExistX(ctx context.Context) bool {
exist, err := bq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the query builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (bq *BoringQuery) Clone() *BoringQuery {
return &BoringQuery{
config: bq.config,
limit: bq.limit,
offset: bq.offset,
order: append([]Order{}, bq.order...),
unique: append([]string{}, bq.unique...),
predicates: append([]predicate.Boring{}, bq.predicates...),
// clone intermediate queries.
sql: bq.sql.Clone(),
gremlin: bq.gremlin.Clone(),
}
}
// GroupBy used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
func (bq *BoringQuery) GroupBy(field string, fields ...string) *BoringGroupBy {
group := &BoringGroupBy{config: bq.config}
group.fields = append([]string{field}, fields...)
switch bq.driver.Dialect() {
case dialect.MySQL, dialect.SQLite:
group.sql = bq.sqlQuery()
case dialect.Neptune:
group.gremlin = bq.gremlinQuery()
}
return group
}
func (bq *BoringQuery) sqlAll(ctx context.Context) ([]*Boring, error) {
rows := &sql.Rows{}
selector := bq.sqlQuery()
if unique := bq.unique; len(unique) == 0 {
selector.Distinct()
}
query, args := selector.Query()
if err := bq.driver.Query(ctx, query, args, rows); err != nil {
return nil, err
}
defer rows.Close()
var bs Borings
if err := bs.FromRows(rows); err != nil {
return nil, err
}
bs.config(bq.config)
return bs, nil
}
func (bq *BoringQuery) sqlCount(ctx context.Context) (int, error) {
rows := &sql.Rows{}
selector := bq.sqlQuery()
unique := []string{boring.FieldID}
if len(bq.unique) > 0 {
unique = bq.unique
}
selector.Count(sql.Distinct(selector.Columns(unique...)...))
query, args := selector.Query()
if err := bq.driver.Query(ctx, query, args, rows); err != nil {
return 0, err
}
defer rows.Close()
if !rows.Next() {
return 0, errors.New("ent: no rows found")
}
var n int
if err := rows.Scan(&n); err != nil {
return 0, fmt.Errorf("ent: failed reading count: %v", err)
}
return n, nil
}
func (bq *BoringQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := bq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("ent: check existence: %v", err)
}
return n > 0, nil
}
func (bq *BoringQuery) sqlIDs(ctx context.Context) ([]string, error) {
vs, err := bq.sqlAll(ctx)
if err != nil {
return nil, err
}
var ids []string
for _, v := range vs {
ids = append(ids, v.ID)
}
return ids, nil
}
func (bq *BoringQuery) sqlQuery() *sql.Selector {
t1 := sql.Table(boring.Table)
selector := sql.Select(t1.Columns(boring.Columns...)...).From(t1)
if bq.sql != nil {
selector = bq.sql
selector.Select(selector.Columns(boring.Columns...)...)
}
for _, p := range bq.predicates {
p(selector)
}
for _, p := range bq.order {
p(selector)
}
if offset := bq.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.MaxInt64)
}
if limit := bq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
func (bq *BoringQuery) gremlinIDs(ctx context.Context) ([]string, error) {
res := &gremlin.Response{}
query, bindings := bq.gremlinQuery().Query()
if err := bq.driver.Exec(ctx, query, bindings, res); err != nil {
return nil, err
}
vertices, err := res.ReadVertices()
if err != nil {
return nil, err
}
ids := make([]string, 0, len(vertices))
for _, vertex := range vertices {
ids = append(ids, vertex.ID.(string))
}
return ids, nil
}
func (bq *BoringQuery) gremlinAll(ctx context.Context) ([]*Boring, error) {
res := &gremlin.Response{}
query, bindings := bq.gremlinQuery().ValueMap(true).Query()
if err := bq.driver.Exec(ctx, query, bindings, res); err != nil {
return nil, err
}
var bs Borings
if err := bs.FromResponse(res); err != nil {
return nil, err
}
bs.config(bq.config)
return bs, nil
}
func (bq *BoringQuery) gremlinCount(ctx context.Context) (int, error) {
res := &gremlin.Response{}
query, bindings := bq.gremlinQuery().Count().Query()
if err := bq.driver.Exec(ctx, query, bindings, res); err != nil {
return 0, err
}
return res.ReadInt()
}
func (bq *BoringQuery) gremlinExist(ctx context.Context) (bool, error) {
res := &gremlin.Response{}
query, bindings := bq.gremlinQuery().HasNext().Query()
if err := bq.driver.Exec(ctx, query, bindings, res); err != nil {
return false, err
}
return res.ReadBool()
}
func (bq *BoringQuery) gremlinQuery() *dsl.Traversal {
v := g.V().HasLabel(boring.Label)
if bq.gremlin != nil {
v = bq.gremlin.Clone()
}
for _, p := range bq.predicates {
p(v)
}
if len(bq.order) > 0 {
v.Order()
for _, p := range bq.order {
p(v)
}
}
switch limit, offset := bq.limit, bq.offset; {
case limit != nil && offset != nil:
v.Range(*offset, *offset+*limit)
case offset != nil:
v.Range(*offset, math.MaxInt64)
case limit != nil:
v.Limit(*limit)
}
if unique := bq.unique; len(unique) == 0 {
v.Dedup()
}
return v
}
// BoringQuery is the builder for group-by Boring entities.
type BoringGroupBy struct {
config
fields []string
fns []Aggregate
// intermediate queries.
sql *sql.Selector
gremlin *dsl.Traversal
}
// Aggregate adds the given aggregation functions to the group-by query.
func (bgb *BoringGroupBy) Aggregate(fns ...Aggregate) *BoringGroupBy {
bgb.fns = append(bgb.fns, fns...)
return bgb
}
// Scan applies the group-by query and scan the result into the given value.
func (bgb *BoringGroupBy) Scan(ctx context.Context, v interface{}) error {
switch bgb.driver.Dialect() {
case dialect.MySQL, dialect.SQLite:
return bgb.sqlScan(ctx, v)
case dialect.Neptune:
return bgb.gremlinScan(ctx, v)
default:
return errors.New("bgb: unsupported dialect")
}
}
// ScanX is like Scan, but panics if an error occurs.
func (bgb *BoringGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := bgb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by. It is only allowed when querying group-by with one field.
func (bgb *BoringGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(bgb.fields) > 1 {
return nil, errors.New("ent: BoringGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := bgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (bgb *BoringGroupBy) StringsX(ctx context.Context) []string {
v, err := bgb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by. It is only allowed when querying group-by with one field.
func (bgb *BoringGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(bgb.fields) > 1 {
return nil, errors.New("ent: BoringGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := bgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (bgb *BoringGroupBy) IntsX(ctx context.Context) []int {
v, err := bgb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by. It is only allowed when querying group-by with one field.
func (bgb *BoringGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(bgb.fields) > 1 {
return nil, errors.New("ent: BoringGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := bgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (bgb *BoringGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := bgb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by. It is only allowed when querying group-by with one field.
func (bgb *BoringGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(bgb.fields) > 1 {
return nil, errors.New("ent: BoringGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := bgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (bgb *BoringGroupBy) BoolsX(ctx context.Context) []bool {
v, err := bgb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
func (bgb *BoringGroupBy) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := bgb.sqlQuery().Query()
if err := bgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (bgb *BoringGroupBy) sqlQuery() *sql.Selector {
selector := bgb.sql
columns := make([]string, 0, len(bgb.fields)+len(bgb.fns))
columns = append(columns, bgb.fields...)
for _, fn := range bgb.fns {
columns = append(columns, fn.SQL(selector))
}
return selector.Select(columns...).GroupBy(bgb.fields...)
}
func (bgb *BoringGroupBy) gremlinScan(ctx context.Context, v interface{}) error {
res := &gremlin.Response{}
query, bindings := bgb.gremlinQuery().Query()
if err := bgb.driver.Exec(ctx, query, bindings, res); err != nil {
return err
}
if len(bgb.fields)+len(bgb.fns) == 1 {
return res.ReadVal(v)
}
vm, err := res.ReadValueMap()
if err != nil {
return err
}
return vm.Decode(v)
}
func (bgb *BoringGroupBy) gremlinQuery() *dsl.Traversal {
var (
trs []interface{}
names []interface{}
)
for _, fn := range bgb.fns {
name, tr := fn.Gremlin("p", "")
trs = append(trs, tr)
names = append(names, name)
}
for _, f := range bgb.fields {
names = append(names, f)
trs = append(trs, __.As("p").Unfold().Values(f).As(f))
}
return bgb.gremlin.Group().
By(__.Values(bgb.fields...).Fold()).
By(__.Fold().Match(trs...).Select(names...)).
Select(dsl.Values).
Next()
}

View File

@@ -1,224 +0,0 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"fbc/ent/entc/integration/plugin/ent/boring"
"fbc/ent/entc/integration/plugin/ent/predicate"
"fbc/ent/dialect"
"fbc/ent/dialect/gremlin"
"fbc/ent/dialect/gremlin/graph/dsl"
"fbc/ent/dialect/gremlin/graph/dsl/g"
"fbc/ent/dialect/sql"
)
// BoringUpdate is the builder for updating Boring entities.
type BoringUpdate struct {
config
predicates []predicate.Boring
}
// Where adds a new predicate for the builder.
func (bu *BoringUpdate) Where(ps ...predicate.Boring) *BoringUpdate {
bu.predicates = append(bu.predicates, ps...)
return bu
}
// Save executes the query and returns the number of rows/vertices matched by this operation.
func (bu *BoringUpdate) Save(ctx context.Context) (int, error) {
switch bu.driver.Dialect() {
case dialect.MySQL, dialect.SQLite:
return bu.sqlSave(ctx)
case dialect.Neptune:
return bu.gremlinSave(ctx)
default:
return 0, errors.New("ent: unsupported dialect")
}
}
// SaveX is like Save, but panics if an error occurs.
func (bu *BoringUpdate) SaveX(ctx context.Context) int {
affected, err := bu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (bu *BoringUpdate) Exec(ctx context.Context) error {
_, err := bu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (bu *BoringUpdate) ExecX(ctx context.Context) {
if err := bu.Exec(ctx); err != nil {
panic(err)
}
}
func (bu *BoringUpdate) sqlSave(ctx context.Context) (n int, err error) {
selector := sql.Select(boring.FieldID).From(sql.Table(boring.Table))
for _, p := range bu.predicates {
p(selector)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err = bu.driver.Query(ctx, query, args, rows); err != nil {
return 0, err
}
defer rows.Close()
var ids []int
for rows.Next() {
var id int
if err := rows.Scan(&id); err != nil {
return 0, fmt.Errorf("ent: failed reading id: %v", err)
}
ids = append(ids, id)
}
if len(ids) == 0 {
return 0, nil
}
tx, err := bu.driver.Tx(ctx)
if err != nil {
return 0, err
}
if err = tx.Commit(); err != nil {
return 0, err
}
return len(ids), nil
}
func (bu *BoringUpdate) gremlinSave(ctx context.Context) (int, error) {
res := &gremlin.Response{}
query, bindings := bu.gremlin().Query()
if err := bu.driver.Exec(ctx, query, bindings, res); err != nil {
return 0, err
}
if err, ok := isConstantError(res); ok {
return 0, err
}
return res.ReadInt()
}
func (bu *BoringUpdate) gremlin() *dsl.Traversal {
v := g.V().HasLabel(boring.Label)
for _, p := range bu.predicates {
p(v)
}
var (
trs []*dsl.Traversal
)
v.Count()
trs = append(trs, v)
return dsl.Join(trs...)
}
// BoringUpdateOne is the builder for updating a single Boring entity.
type BoringUpdateOne struct {
config
id string
}
// Save executes the query and returns the updated entity.
func (buo *BoringUpdateOne) Save(ctx context.Context) (*Boring, error) {
switch buo.driver.Dialect() {
case dialect.MySQL, dialect.SQLite:
return buo.sqlSave(ctx)
case dialect.Neptune:
return buo.gremlinSave(ctx)
default:
return nil, errors.New("ent: unsupported dialect")
}
}
// SaveX is like Save, but panics if an error occurs.
func (buo *BoringUpdateOne) SaveX(ctx context.Context) *Boring {
b, err := buo.Save(ctx)
if err != nil {
panic(err)
}
return b
}
// Exec executes the query on the entity.
func (buo *BoringUpdateOne) Exec(ctx context.Context) error {
_, err := buo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (buo *BoringUpdateOne) ExecX(ctx context.Context) {
if err := buo.Exec(ctx); err != nil {
panic(err)
}
}
func (buo *BoringUpdateOne) sqlSave(ctx context.Context) (b *Boring, err error) {
selector := sql.Select(boring.Columns...).From(sql.Table(boring.Table))
boring.ID(buo.id)(selector)
rows := &sql.Rows{}
query, args := selector.Query()
if err = buo.driver.Query(ctx, query, args, rows); err != nil {
return nil, err
}
defer rows.Close()
var ids []int
for rows.Next() {
var id int
b = &Boring{config: buo.config}
if err := b.FromRows(rows); err != nil {
return nil, fmt.Errorf("ent: failed scanning row into Boring: %v", err)
}
id = b.id()
ids = append(ids, id)
}
switch n := len(ids); {
case n == 0:
return nil, fmt.Errorf("ent: Boring not found with id: %v", buo.id)
case n > 1:
return nil, fmt.Errorf("ent: more than one Boring with the same id: %v", buo.id)
}
tx, err := buo.driver.Tx(ctx)
if err != nil {
return nil, err
}
if err = tx.Commit(); err != nil {
return nil, err
}
return b, nil
}
func (buo *BoringUpdateOne) gremlinSave(ctx context.Context) (*Boring, error) {
res := &gremlin.Response{}
query, bindings := buo.gremlin(buo.id).Query()
if err := buo.driver.Exec(ctx, query, bindings, res); err != nil {
return nil, err
}
if err, ok := isConstantError(res); ok {
return nil, err
}
b := &Boring{config: buo.config}
if err := b.FromResponse(res); err != nil {
return nil, err
}
return b, nil
}
func (buo *BoringUpdateOne) gremlin(id string) *dsl.Traversal {
v := g.V(id)
var (
trs []*dsl.Traversal
)
v.ValueMap(true)
trs = append(trs, v)
return dsl.Join(trs...)
}

View File

@@ -1,99 +0,0 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"log"
"fbc/ent/entc/integration/plugin/ent/migrate"
"fbc/ent/entc/integration/plugin/ent/boring"
)
// Client is the client that holds all ent builders.
type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// Boring is the client for interacting with the Boring builders.
Boring *BoringClient
}
// NewClient creates a new client configured with the given options.
func NewClient(opts ...Option) *Client {
c := config{log: log.Println}
c.options(opts...)
return &Client{
config: c,
Schema: migrate.NewSchema(c.driver),
Boring: NewBoringClient(c),
}
}
// Tx returns a new transactional client.
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, fmt.Errorf("ent: cannot start a transaction within a transaction")
}
tx, err := newTx(ctx, c.driver)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %v", err)
}
cfg := config{driver: tx, log: c.log, verbose: c.verbose}
return &Tx{
config: cfg,
Boring: NewBoringClient(cfg),
}, nil
}
// BoringClient is a client for the Boring schema.
type BoringClient struct {
config
}
// NewBoringClient returns a client for the Boring from the given config.
func NewBoringClient(c config) *BoringClient {
return &BoringClient{config: c}
}
// Create returns a create builder for Boring.
func (c *BoringClient) Create() *BoringCreate {
return &BoringCreate{config: c.config}
}
// Update returns an update builder for Boring.
func (c *BoringClient) Update() *BoringUpdate {
return &BoringUpdate{config: c.config}
}
// UpdateOne returns an update builder for the given entity.
func (c *BoringClient) UpdateOne(b *Boring) *BoringUpdateOne {
return c.UpdateOneID(b.ID)
}
// UpdateOneID returns an update builder for the given id.
func (c *BoringClient) UpdateOneID(id string) *BoringUpdateOne {
return &BoringUpdateOne{config: c.config, id: id}
}
// Delete returns a delete builder for Boring.
func (c *BoringClient) Delete() *BoringDelete {
return &BoringDelete{config: c.config}
}
// DeleteOne returns a delete builder for the given entity.
func (c *BoringClient) DeleteOne(b *Boring) *BoringDeleteOne {
return c.DeleteOneID(b.ID)
}
// DeleteOneID returns a delete builder for the given id.
func (c *BoringClient) DeleteOneID(id string) *BoringDeleteOne {
return &BoringDeleteOne{c.Delete().Where(boring.ID(id))}
}
// Create returns a query builder for Boring.
func (c *BoringClient) Query() *BoringQuery {
return &BoringQuery{config: c.config}
}

View File

@@ -1,51 +0,0 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"fbc/ent/dialect"
)
// Option function to configure the client.
type Option func(*config)
// Config is the configuration for the client and its builder.
type config struct {
// driver is the driver used for execute database requests.
driver dialect.Driver
// verbose enable a verbosity logging.
verbose bool
// log used for logging on verbose mode.
log func(...interface{})
}
// Options applies the options on the config object.
func (c *config) options(opts ...Option) {
for _, opt := range opts {
opt(c)
}
if c.verbose {
c.driver = dialect.Debug(c.driver, c.log)
}
}
// Verbose sets the client logging to verbose.
func Verbose() Option {
return func(c *config) {
c.verbose = true
}
}
// Log sets the client logging to verbose.
func Log(fn func(...interface{})) Option {
return func(c *config) {
c.log = fn
}
}
// Driver configures the client driver.
func Driver(driver dialect.Driver) Option {
return func(c *config) {
c.driver = driver
}
}

View File

@@ -1,20 +0,0 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
)
type contextKey struct{}
// FromContext returns the Client stored in a context, or nil if there isn't one.
func FromContext(ctx context.Context) *Client {
c, _ := ctx.Value(contextKey{}).(*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, contextKey{}, c)
}

View File

@@ -1,329 +0,0 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"fmt"
"strconv"
"strings"
"fbc/ent/dialect"
"fbc/ent/dialect/gremlin"
"fbc/ent/dialect/gremlin/encoding/graphson"
"fbc/ent/dialect/gremlin/graph/dsl"
"fbc/ent/dialect/gremlin/graph/dsl/__"
"fbc/ent/dialect/sql"
)
// Order applies an ordering on either graph traversal or sql selector.
type Order func(interface{})
// OrderPerDialect construct the "order by" clause for graph traversals based on dialect type.
func OrderPerDialect(f0 func(*sql.Selector), f1 func(*dsl.Traversal)) Order {
return Order(func(v interface{}) {
switch v := v.(type) {
case *sql.Selector:
f0(v)
case *dsl.Traversal:
f1(v)
default:
panic(fmt.Sprintf("unknown type for order: %T", v))
}
})
}
// Asc applies the given fields in ASC order.
func Asc(fields ...string) Order {
return OrderPerDialect(
func(s *sql.Selector) {
for _, f := range fields {
s.OrderBy(sql.Asc(f))
}
},
func(tr *dsl.Traversal) {
for _, f := range fields {
tr.By(f, dsl.Incr)
}
},
)
}
// Desc applies the given fields in DESC order.
func Desc(fields ...string) Order {
return OrderPerDialect(
func(s *sql.Selector) {
for _, f := range fields {
s.OrderBy(sql.Desc(f))
}
},
func(tr *dsl.Traversal) {
for _, f := range fields {
tr.By(f, dsl.Decr)
}
},
)
}
// Aggregate applies an aggregation step on the group-by traversal/selector.
type Aggregate struct {
// SQL the column wrapped with the aggregation function.
SQL func(*sql.Selector) string
// Gremlin gets two labels as parameters. The first used in the `As` step for the predicate,
// and the second is an optional name for the next predicates (or for later usage).
Gremlin func(string, string) (string, *dsl.Traversal)
}
// 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 Aggregate, end string) Aggregate {
return Aggregate{
SQL: func(s *sql.Selector) string {
return sql.As(fn.SQL(s), end)
},
Gremlin: func(start, _ string) (string, *dsl.Traversal) {
return fn.Gremlin(start, end)
},
}
}
// DefaultCountLabel is the default label name for the Count aggregation function.
// It should be used as the struct-tag for decoding, or a map key for interaction with the returned response.
// In order to "count" 2 or more fields and avoid conflicting, use the `ent.As(ent.Count(field), "custom_name")`
// function with custom name in order to override it.
const DefaultCountLabel = "count"
// Count applies the "count" aggregation function on each group.
func Count() Aggregate {
return Aggregate{
SQL: func(s *sql.Selector) string {
return sql.Count("*")
},
Gremlin: func(start, end string) (string, *dsl.Traversal) {
if end == "" {
end = DefaultCountLabel
}
return end, __.As(start).Count(dsl.Local).As(end)
},
}
}
// DefaultMaxLabel is the default label name for the Max aggregation function.
// It should be used as the struct-tag for decoding, or a map key for interaction with the returned response.
// In order to "max" 2 or more fields and avoid conflicting, use the `ent.As(ent.Max(field), "custom_name")`
// function with custom name in order to override it.
const DefaultMaxLabel = "max"
// Max applies the "max" aggregation function on the given field of each group.
func Max(field string) Aggregate {
return Aggregate{
SQL: func(s *sql.Selector) string {
return sql.Max(s.C(field))
},
Gremlin: func(start, end string) (string, *dsl.Traversal) {
if end == "" {
end = DefaultMaxLabel
}
return end, __.As(start).Unfold().Values(field).Max().As(end)
},
}
}
// DefaultMeanLabel is the default label name for the Mean aggregation function.
// It should be used as the struct-tag for decoding, or a map key for interaction with the returned response.
// In order to "mean" 2 or more fields and avoid conflicting, use the `ent.As(ent.Mean(field), "custom_name")`
// function with custom name in order to override it.
const DefaultMeanLabel = "mean"
// Mean applies the "mean" aggregation function on the given field of each group.
func Mean(field string) Aggregate {
return Aggregate{
SQL: func(s *sql.Selector) string {
return sql.Avg(s.C(field))
},
Gremlin: func(start, end string) (string, *dsl.Traversal) {
if end == "" {
end = DefaultMeanLabel
}
return end, __.As(start).Unfold().Values(field).Mean().As(end)
},
}
}
// DefaultMinLabel is the default label name for the Min aggregation function.
// It should be used as the struct-tag for decoding, or a map key for interaction with the returned response.
// In order to "min" 2 or more fields and avoid conflicting, use the `ent.As(ent.Min(field), "custom_name")`
// function with custom name in order to override it.
const DefaultMinLabel = "min"
// Min applies the "min" aggregation function on the given field of each group.
func Min(field string) Aggregate {
return Aggregate{
SQL: func(s *sql.Selector) string {
return sql.Min(s.C(field))
},
Gremlin: func(start, end string) (string, *dsl.Traversal) {
if end == "" {
end = DefaultMinLabel
}
return end, __.As(start).Unfold().Values(field).Min().As(end)
},
}
}
// DefaultSumLabel is the default label name for the Sum aggregation function.
// It should be used as the struct-tag for decoding, or a map key for interaction with the returned response.
// In order to "sum" 2 or more fields and avoid conflicting, use the `ent.As(ent.Sum(field), "custom_name")`
// function with custom name in order to override it.
const DefaultSumLabel = "sum"
// Sum applies the "sum" aggregation function on the given field of each group.
func Sum(field string) Aggregate {
return Aggregate{
SQL: func(s *sql.Selector) string {
return sql.Sum(s.C(field))
},
Gremlin: func(start, end string) (string, *dsl.Traversal) {
if end == "" {
end = DefaultSumLabel
}
return end, __.As(start).Unfold().Values(field).Sum().As(end)
},
}
}
// ErrNotFound returns when trying to fetch a specific entity and it was not found in the database.
type ErrNotFound struct {
label string
}
// Error implements the error interface.
func (e *ErrNotFound) Error() string {
return fmt.Sprintf("ent: %s not found", e.label)
}
// IsNotFound returns a boolean indicating whether the error is a not found error.
func IsNotFound(err error) bool {
_, ok := err.(*ErrNotFound)
return ok
}
// MaskNotFound masks nor found error.
func MaskNotFound(err error) error {
if IsNotFound(err) {
return nil
}
return err
}
// ErrNotSingular returns when trying to fetch a singular entity and more then one was found in the database.
type ErrNotSingular struct {
label string
}
// Error implements the error interface.
func (e *ErrNotSingular) Error() string {
return fmt.Sprintf("ent: %s not singular", e.label)
}
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
func IsNotSingular(err error) bool {
_, ok := err.(*ErrNotSingular)
return ok
}
// ErrConstraintFailed 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 ErrConstraintFailed struct {
msg string
wrap error
}
// Error implements the error interface.
func (e ErrConstraintFailed) Error() string {
return fmt.Sprintf("ent: unique constraint failed: %s", e.msg)
}
// Unwrap implements the errors.Wrapper interface.
func (e *ErrConstraintFailed) Unwrap() error {
return e.wrap
}
// IsConstraintFailure returns a boolean indicating whether the error is a constraint failure.
func IsConstraintFailure(err error) bool {
_, ok := err.(*ErrConstraintFailed)
return ok
}
func isSQLConstraintError(err error) (*ErrConstraintFailed, bool) {
// Error number 1062 is ER_DUP_ENTRY in mysql, and "UNIQUE constraint failed" is SQLite prefix.
if msg := err.Error(); strings.HasPrefix(msg, "Error 1062") || strings.HasPrefix(msg, "UNIQUE constraint failed") {
return &ErrConstraintFailed{msg, err}, true
}
return nil, false
}
// rollback calls to tx.Rollback and wraps the given error with the rollback error if occurred.
func rollback(tx dialect.Tx, err error) error {
if rerr := tx.Rollback(); rerr != nil {
err = fmt.Errorf("%s: %v", err.Error(), rerr)
}
if err, ok := isSQLConstraintError(err); ok {
return err
}
return err
}
// Code implements the dsl.Node interface.
func (e ErrConstraintFailed) Code() (string, []interface{}) {
return strconv.Quote(e.prefix() + e.msg), nil
}
func (e *ErrConstraintFailed) UnmarshalGraphson(b []byte) error {
var v [1]*string
if err := graphson.Unmarshal(b, &v); err != nil {
return err
}
if v[0] == nil {
return fmt.Errorf("ent: missing string value")
}
if !strings.HasPrefix(*v[0], e.prefix()) {
return fmt.Errorf("ent: invalid string for error: %s", *v[0])
}
e.msg = strings.TrimPrefix(*v[0], e.prefix())
return nil
}
// prefix returns the prefix used for gremlin constants.
func (ErrConstraintFailed) prefix() string { return "Error: " }
// NewErrUniqueField creates a constraint error for unique fields.
func NewErrUniqueField(label, field string, v interface{}) *ErrConstraintFailed {
return &ErrConstraintFailed{msg: fmt.Sprintf("field %s.%s with value: %#v", label, field, v)}
}
// NewErrUniqueEdge creates a constraint error for unique edges.
func NewErrUniqueEdge(label, edge, id string) *ErrConstraintFailed {
return &ErrConstraintFailed{msg: fmt.Sprintf("edge %s.%s with id: %#v", label, edge, id)}
}
// isConstantError indicates if the given response holds a gremlin constant containing an error.
func isConstantError(r *gremlin.Response) (*ErrConstraintFailed, bool) {
e := &ErrConstraintFailed{}
if err := graphson.Unmarshal(r.Result.Data, e); err != nil {
return nil, false
}
return e, true
}
// keys returns the keys/ids from the edge map.
func keys(m map[string]struct{}) []string {
s := make([]string, 0, len(m))
for id, _ := range m {
s = append(s, id)
}
return s
}

View File

@@ -1,40 +0,0 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"log"
"fbc/ent/dialect/sql"
)
// dsn for the database. In order to run the tests locally, run the following command:
//
// ENT_INTEGRATION_ENDPOINT="root:pass@tcp(localhost:3306)/test?parseTime=True" go test -v
//
var dsn string
func ExampleBoring() {
if dsn == "" {
return
}
ctx := context.Background()
drv, err := sql.Open("mysql", dsn)
if err != nil {
log.Fatalf("failed creating database client: %v", err)
}
defer drv.Close()
client := NewClient(Driver(drv))
// creating vertices for the boring's edges.
// create boring vertex with its edges.
b := client.Boring.
Create().
SaveX(ctx)
log.Println("boring created:", b)
// query edges.
// Output:
}

View File

@@ -1,29 +0,0 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package migrate
import (
"context"
"fmt"
"fbc/ent/dialect"
"fbc/ent/dialect/sql/schema"
)
// Schema is the API for creating, migrating and dropping a schema.
type Schema struct {
drv dialect.Driver
universalID bool
}
// 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 {
migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %v", err)
}
return migrate.Create(ctx, Tables...)
}

View File

@@ -1,30 +0,0 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package migrate
import (
"fbc/ent/dialect/sql/schema"
"fbc/ent/field"
)
var (
nullable = true
// BoringsColumns holds the columns for the "borings" table.
BoringsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
}
// BoringsTable holds the schema information for the "borings" table.
BoringsTable = &schema.Table{
Name: "borings",
Columns: BoringsColumns,
PrimaryKey: []*schema.Column{BoringsColumns[0]},
ForeignKeys: []*schema.ForeignKey{},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
BoringsTable,
}
)
func init() {
}

View File

@@ -1,27 +0,0 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package predicate
import (
"fmt"
"fbc/ent/dialect/gremlin/graph/dsl"
"fbc/ent/dialect/sql"
)
// Boring is the predicate function for boring builders.
type Boring func(interface{})
// BoringPerDialect construct a predicate for graph traversals based on dialect type.
func BoringPerDialect(f0 func(*sql.Selector), f1 func(*dsl.Traversal)) Boring {
return Boring(func(v interface{}) {
switch v := v.(type) {
case *sql.Selector:
f0(v)
case *dsl.Traversal:
f1(v)
default:
panic(fmt.Sprintf("unknown type for predicate: %T", v))
}
})
}

View File

@@ -1,18 +0,0 @@
package schema
import "fbc/ent"
// Boring holds the schema definition for the Boring entity.
type Boring struct {
ent.Schema
}
// Fields of the Boring.
func (Boring) Fields() []ent.Field {
return nil
}
// Edges of the Boring.
func (Boring) Edges() []ent.Edge {
return nil
}

View File

@@ -1,93 +0,0 @@
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"fbc/ent/dialect"
"fbc/ent/entc/integration/plugin/ent/migrate"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Boring is the client for interacting with the Boring builders.
Boring *BoringClient
}
// Commit commits the transaction.
func (tx *Tx) Commit() error {
return tx.config.driver.(*txDriver).tx.Commit()
}
// Rollback rollbacks the transaction.
func (tx *Tx) Rollback() error {
return tx.config.driver.(*txDriver).tx.Rollback()
}
// Client returns a Client that binds to current transaction.
func (tx *Tx) Client() *Client {
return &Client{
config: tx.config,
Schema: migrate.NewSchema(tx.driver),
Boring: NewBoringClient(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: Boring.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
}
// 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 interface{}, v interface{}) error {
return tx.tx.Exec(ctx, query, args, v)
}
// Query calls tx.Query.
func (tx *txDriver) Query(ctx context.Context, query string, args interface{}, v interface{}) error {
return tx.tx.Query(ctx, query, args, v)
}
var _ dialect.Driver = (*txDriver)(nil)

View File

@@ -1,38 +0,0 @@
package plugin
import (
"bytes"
"fmt"
"os"
"os/exec"
"testing"
"github.com/stretchr/testify/require"
)
func TestPlugin(t *testing.T) {
plg := "printer.so"
// build entc plugin.
cmd := exec.Command("go", "build", "-o", plg, "-buildmode", "plugin", "./testdata")
_, err := run(cmd)
require.NoError(t, err)
defer os.Remove(plg)
// execute entc generate and expect the plugin to be executed.
cmd = exec.Command("go", "run", "../../cmd/entc/entc.go", "generate", "--storage", "sql,gremlin", "--plugin", plg, "./ent/schema")
out, err := run(cmd)
require.NoError(t, err)
require.Equal(t, "Boring\n", out, "printer plugin should print node names")
}
func run(cmd *exec.Cmd) (string, error) {
out := bytes.NewBuffer(nil)
cmd.Stderr = out
cmd.Stdout = out
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("integration/plugin: %s", out)
}
return out.String(), nil
}

View File

@@ -1,16 +0,0 @@
package main
import (
"fmt"
"fbc/ent/entc/gen"
"fbc/ent/entc/plugin"
)
// Gen is the required plugin symbol.
var Gen = plugin.GeneratorFunc(func(graph *gen.Graph) error {
for _, n := range graph.Nodes {
fmt.Println(n.Name)
}
return nil
})