schema/field: json type support (#38)

Summary:
Pull Request resolved: https://github.com/facebookincubator/ent/pull/38

Only `IsNil` and `NotNil` predicates are supported this moment

Reviewed By: alexsn

Differential Revision: D17444976

fbshipit-source-id: 37336fa0bc7749af995933baee2e23bb7366dd78
This commit is contained in:
Ariel Mashraki
2019-09-19 04:58:21 -07:00
committed by Facebook Github Bot
parent 83d0063437
commit c3955a08f1
214 changed files with 4005 additions and 1296 deletions

View File

@@ -0,0 +1,138 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"log"
"github.com/facebookincubator/ent/entc/integration/json/ent/migrate"
"github.com/facebookincubator/ent/entc/integration/json/ent/user"
"github.com/facebookincubator/ent/dialect"
)
// 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
// User is the client for interacting with the User builders.
User *UserClient
}
// NewClient creates a new client configured with the given options.
func NewClient(opts ...Option) *Client {
c := config{log: log.Println}
c.options(opts...)
return &Client{
config: c,
Schema: migrate.NewSchema(c.driver),
User: NewUserClient(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, debug: c.debug}
return &Tx{
config: cfg,
User: NewUserClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// User.
// Query().
// Count(ctx)
//
func (c *Client) Debug() *Client {
if c.debug {
return c
}
cfg := config{driver: dialect.Debug(c.driver, c.log), log: c.log, debug: true}
return &Client{
config: cfg,
Schema: migrate.NewSchema(cfg.driver),
User: NewUserClient(cfg),
}
}
// UserClient is a client for the User schema.
type UserClient struct {
config
}
// NewUserClient returns a client for the User from the given config.
func NewUserClient(c config) *UserClient {
return &UserClient{config: c}
}
// Create returns a create builder for User.
func (c *UserClient) Create() *UserCreate {
return &UserCreate{config: c.config}
}
// Update returns an update builder for User.
func (c *UserClient) Update() *UserUpdate {
return &UserUpdate{config: c.config}
}
// UpdateOne returns an update builder for the given entity.
func (c *UserClient) UpdateOne(u *User) *UserUpdateOne {
return c.UpdateOneID(u.ID)
}
// UpdateOneID returns an update builder for the given id.
func (c *UserClient) UpdateOneID(id int) *UserUpdateOne {
return &UserUpdateOne{config: c.config, id: id}
}
// Delete returns a delete builder for User.
func (c *UserClient) Delete() *UserDelete {
return &UserDelete{config: c.config}
}
// DeleteOne returns a delete builder for the given entity.
func (c *UserClient) DeleteOne(u *User) *UserDeleteOne {
return c.DeleteOneID(u.ID)
}
// DeleteOneID returns a delete builder for the given id.
func (c *UserClient) DeleteOneID(id int) *UserDeleteOne {
return &UserDeleteOne{c.Delete().Where(user.ID(id))}
}
// Create returns a query builder for User.
func (c *UserClient) Query() *UserQuery {
return &UserQuery{config: c.config}
}
// Get returns a User entity by its id.
func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {
return c.Query().Where(user.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *UserClient) GetX(ctx context.Context, id int) *User {
u, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return u
}

View File

@@ -0,0 +1,55 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"github.com/facebookincubator/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 used for executing database requests.
driver dialect.Driver
// debug enable a debug logging.
debug bool
// log used for logging on debug 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.debug {
c.driver = dialect.Debug(c.driver, c.log)
}
}
// Debug enables debug logging on the ent.Driver.
func Debug() Option {
return func(c *config) {
c.debug = true
}
}
// Log sets the logging function for debug mode.
func Log(fn func(...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

@@ -0,0 +1,24 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// 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

@@ -0,0 +1,196 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"github.com/facebookincubator/ent/dialect"
"github.com/facebookincubator/ent/dialect/sql"
)
// Order applies an ordering on either graph traversal or sql selector.
type Order func(*sql.Selector)
// Asc applies the given fields in ASC order.
func Asc(fields ...string) Order {
return Order(
func(s *sql.Selector) {
for _, f := range fields {
s.OrderBy(sql.Asc(f))
}
},
)
}
// Desc applies the given fields in DESC order.
func Desc(fields ...string) Order {
return Order(
func(s *sql.Selector) {
for _, f := range fields {
s.OrderBy(sql.Desc(f))
}
},
)
}
// 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
}
// 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)
},
}
}
// Count applies the "count" aggregation function on each group.
func Count() Aggregate {
return Aggregate{
SQL: func(s *sql.Selector) string {
return sql.Count("*")
},
}
}
// Max applies the "max" aggregation function on the given field of each group.
func Max(field string) Aggregate {
return Aggregate{
SQL: func(s *sql.Selector) string {
return sql.Max(s.C(field))
},
}
}
// 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))
},
}
}
// 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))
},
}
}
// 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))
},
}
}
// 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
}
// keys returns the keys/ids from the edge map.
func keys(m map[int]struct{}) []int {
s := make([]int, 0, len(m))
for id, _ := range m {
s = append(s, id)
}
return s
}

View File

@@ -0,0 +1,50 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"log"
"github.com/facebookincubator/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 ExampleUser() {
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 user's edges.
// create user vertex with its edges.
u := client.User.
Create().
SetURL(nil).
SetRaw(nil).
SetDirs(nil).
SetInts(nil).
SetFloats(nil).
SetStrings(nil).
SaveX(ctx)
log.Println("user created:", u)
// query edges.
// Output:
}

View File

@@ -0,0 +1,71 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated (@generated) by entc, DO NOT EDIT.
package migrate
import (
"context"
"fmt"
"io"
"github.com/facebookincubator/ent/dialect"
"github.com/facebookincubator/ent/dialect/sql/schema"
)
var (
// WithGlobalUniqueID sets the universal ids options to the migration.
// If this option is enabled, ent migration will allocate a 1<<32 range
// for the ids of each entity (table).
// Note that this option cannot be applied on tables that already exist.
WithGlobalUniqueID = schema.WithGlobalUniqueID
// WithDropColumn sets the drop column option to the migration.
// If this option is enabled, ent migration will drop old columns
// that were used for both fields and edges. This defaults to false.
WithDropColumn = schema.WithDropColumn
// WithDropIndex sets the drop index option to the migration.
// If this option is enabled, ent migration will drop old indexes
// that were defined in the schema. This defaults to false.
// Note that unique constraints are defined using `UNIQUE INDEX`,
// and therefore, it's recommended to enable this option to get more
// flexibility in the schema changes.
WithDropIndex = schema.WithDropIndex
)
// 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...)
}
// WriteTo writes the schema changes to w instead of running them against the database.
//
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
// log.Fatal(err)
// }
//
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
drv := &schema.WriteDriver{
Writer: w,
Driver: s.drv,
}
migrate, err := schema.NewMigrate(drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %v", err)
}
return migrate.Create(ctx, Tables...)
}

View File

@@ -0,0 +1,39 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated (@generated) by entc, DO NOT EDIT.
package migrate
import (
"github.com/facebookincubator/ent/dialect/sql/schema"
"github.com/facebookincubator/ent/schema/field"
)
var (
// UsersColumns holds the columns for the "users" table.
UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "url", Type: field.TypeJSON, Nullable: true},
{Name: "raw", Type: field.TypeJSON, Nullable: true},
{Name: "dirs", Type: field.TypeJSON, Nullable: true},
{Name: "ints", Type: field.TypeJSON, Nullable: true},
{Name: "floats", Type: field.TypeJSON, Nullable: true},
{Name: "strings", Type: field.TypeJSON, Nullable: true},
}
// UsersTable holds the schema information for the "users" table.
UsersTable = &schema.Table{
Name: "users",
Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]},
ForeignKeys: []*schema.ForeignKey{},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
UsersTable,
}
)
func init() {
}

View File

@@ -0,0 +1,14 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated (@generated) by entc, DO NOT EDIT.
package predicate
import (
"github.com/facebookincubator/ent/dialect/sql"
)
// User is the predicate function for user builders.
type User func(*sql.Selector)

View File

@@ -0,0 +1,33 @@
package schema
import (
"encoding/json"
"net/http"
"net/url"
"github.com/facebookincubator/ent"
"github.com/facebookincubator/ent/schema/field"
)
// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.JSON("url", &url.URL{}).
Optional(),
field.JSON("raw", json.RawMessage{}).
Optional(),
field.JSON("dirs", []http.Dir{}).
Optional(),
field.Ints("ints").
Optional(),
field.Floats("floats").
Optional(),
field.Strings("strings").
Optional(),
}
}

View File

@@ -0,0 +1,97 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"github.com/facebookincubator/ent/dialect"
"github.com/facebookincubator/ent/entc/integration/json/ent/migrate"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// User is the client for interacting with the User builders.
User *UserClient
}
// 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),
User: NewUserClient(tx.config),
}
}
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
// The idea is to support transactions without adding any extra code to the builders.
// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance.
// Commit and Rollback are nop for the internal builders and the user must call one
// of them in order to commit or rollback the transaction.
//
// If a closed transaction is embedded in one of the generated entities, and the entity
// applies a query, for example: User.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, 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, v interface{}) error {
return tx.tx.Query(ctx, query, args, v)
}
var _ dialect.Driver = (*txDriver)(nil)

View File

@@ -0,0 +1,147 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
"github.com/facebookincubator/ent/dialect/sql"
)
// User is the model entity for the User schema.
type User struct {
config
// ID of the ent.
ID int `json:"id,omitempty"`
// URL holds the value of the "url" field.
URL *url.URL `json:"url,omitempty"`
// Raw holds the value of the "raw" field.
Raw json.RawMessage `json:"raw,omitempty"`
// Dirs holds the value of the "dirs" field.
Dirs []http.Dir `json:"dirs,omitempty"`
// Ints holds the value of the "ints" field.
Ints []int `json:"ints,omitempty"`
// Floats holds the value of the "floats" field.
Floats []float64 `json:"floats,omitempty"`
// Strings holds the value of the "strings" field.
Strings []string `json:"strings,omitempty"`
}
// FromRows scans the sql response data into User.
func (u *User) FromRows(rows *sql.Rows) error {
var vu struct {
ID int
URL []byte
Raw []byte
Dirs []byte
Ints []byte
Floats []byte
Strings []byte
}
// the order here should be the same as in the `user.Columns`.
if err := rows.Scan(
&vu.ID,
&vu.URL,
&vu.Raw,
&vu.Dirs,
&vu.Ints,
&vu.Floats,
&vu.Strings,
); err != nil {
return err
}
u.ID = vu.ID
if value := vu.URL; len(value) > 0 {
if err := json.Unmarshal(value, &u.URL); err != nil {
return fmt.Errorf("unmarshal field url: %v", err)
}
}
if value := vu.Raw; len(value) > 0 {
if err := json.Unmarshal(value, &u.Raw); err != nil {
return fmt.Errorf("unmarshal field raw: %v", err)
}
}
if value := vu.Dirs; len(value) > 0 {
if err := json.Unmarshal(value, &u.Dirs); err != nil {
return fmt.Errorf("unmarshal field dirs: %v", err)
}
}
if value := vu.Ints; len(value) > 0 {
if err := json.Unmarshal(value, &u.Ints); err != nil {
return fmt.Errorf("unmarshal field ints: %v", err)
}
}
if value := vu.Floats; len(value) > 0 {
if err := json.Unmarshal(value, &u.Floats); err != nil {
return fmt.Errorf("unmarshal field floats: %v", err)
}
}
if value := vu.Strings; len(value) > 0 {
if err := json.Unmarshal(value, &u.Strings); err != nil {
return fmt.Errorf("unmarshal field strings: %v", err)
}
}
return nil
}
// Update returns a builder for updating this User.
// Note that, you need to call User.Unwrap() before calling this method, if this User
// was returned from a transaction, and the transaction was committed or rolled back.
func (u *User) Update() *UserUpdateOne {
return (&UserClient{u.config}).UpdateOne(u)
}
// 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 (u *User) Unwrap() *User {
tx, ok := u.config.driver.(*txDriver)
if !ok {
panic("ent: User is not a transactional entity")
}
u.config.driver = tx.drv
return u
}
// String implements the fmt.Stringer.
func (u *User) String() string {
buf := bytes.NewBuffer(nil)
buf.WriteString("User(")
buf.WriteString(fmt.Sprintf("id=%v", u.ID))
buf.WriteString(fmt.Sprintf(", url=%v", u.URL))
buf.WriteString(fmt.Sprintf(", raw=%v", u.Raw))
buf.WriteString(fmt.Sprintf(", dirs=%v", u.Dirs))
buf.WriteString(fmt.Sprintf(", ints=%v", u.Ints))
buf.WriteString(fmt.Sprintf(", floats=%v", u.Floats))
buf.WriteString(fmt.Sprintf(", strings=%v", u.Strings))
buf.WriteString(")")
return buf.String()
}
// Users is a parsable slice of User.
type Users []*User
// FromRows scans the sql response data into Users.
func (u *Users) FromRows(rows *sql.Rows) error {
for rows.Next() {
vu := &User{}
if err := vu.FromRows(rows); err != nil {
return err
}
*u = append(*u, vu)
}
return nil
}
func (u Users) config(cfg config) {
for i := range u {
u[i].config = cfg
}
}

View File

@@ -0,0 +1,40 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated (@generated) by entc, DO NOT EDIT.
package user
const (
// Label holds the string label denoting the user type in the database.
Label = "user"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldURL holds the string denoting the url vertex property in the database.
FieldURL = "url"
// FieldRaw holds the string denoting the raw vertex property in the database.
FieldRaw = "raw"
// FieldDirs holds the string denoting the dirs vertex property in the database.
FieldDirs = "dirs"
// FieldInts holds the string denoting the ints vertex property in the database.
FieldInts = "ints"
// FieldFloats holds the string denoting the floats vertex property in the database.
FieldFloats = "floats"
// FieldStrings holds the string denoting the strings vertex property in the database.
FieldStrings = "strings"
// Table holds the table name of the user in the database.
Table = "users"
)
// Columns holds all SQL columns are user fields.
var Columns = []string{
FieldID,
FieldURL,
FieldRaw,
FieldDirs,
FieldInts,
FieldFloats,
FieldStrings,
}

View File

@@ -0,0 +1,255 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated (@generated) by entc, DO NOT EDIT.
package user
import (
"github.com/facebookincubator/ent/dialect/sql"
"github.com/facebookincubator/ent/entc/integration/json/ent/predicate"
)
// ID filters vertices based on their identifier.
func ID(id int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
},
)
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
},
)
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
},
)
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
},
)
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
},
)
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
},
)
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
},
)
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.User {
return predicate.User(
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] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
},
)
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.User {
return predicate.User(
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] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
},
)
}
// URLIsNil applies the IsNil predicate on the "url" field.
func URLIsNil() predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldURL)))
},
)
}
// URLNotNil applies the NotNil predicate on the "url" field.
func URLNotNil() predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldURL)))
},
)
}
// RawIsNil applies the IsNil predicate on the "raw" field.
func RawIsNil() predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldRaw)))
},
)
}
// RawNotNil applies the NotNil predicate on the "raw" field.
func RawNotNil() predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldRaw)))
},
)
}
// DirsIsNil applies the IsNil predicate on the "dirs" field.
func DirsIsNil() predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldDirs)))
},
)
}
// DirsNotNil applies the NotNil predicate on the "dirs" field.
func DirsNotNil() predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldDirs)))
},
)
}
// IntsIsNil applies the IsNil predicate on the "ints" field.
func IntsIsNil() predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldInts)))
},
)
}
// IntsNotNil applies the NotNil predicate on the "ints" field.
func IntsNotNil() predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldInts)))
},
)
}
// FloatsIsNil applies the IsNil predicate on the "floats" field.
func FloatsIsNil() predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldFloats)))
},
)
}
// FloatsNotNil applies the NotNil predicate on the "floats" field.
func FloatsNotNil() predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldFloats)))
},
)
}
// StringsIsNil applies the IsNil predicate on the "strings" field.
func StringsIsNil() predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldStrings)))
},
)
}
// StringsNotNil applies the NotNil predicate on the "strings" field.
func StringsNotNil() predicate.User {
return predicate.User(
func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldStrings)))
},
)
}
// And groups list of predicates with the AND operator between them.
func And(predicates ...predicate.User) predicate.User {
return predicate.User(
func(s *sql.Selector) {
for _, p := range predicates {
p(s)
}
},
)
}
// Or groups list of predicates with the OR operator between them.
func Or(predicates ...predicate.User) predicate.User {
return predicate.User(
func(s *sql.Selector) {
for i, p := range predicates {
if i > 0 {
s.Or()
}
p(s)
}
},
)
}
// Not applies the not operator on the given predicate.
func Not(p predicate.User) predicate.User {
return predicate.User(
func(s *sql.Selector) {
p(s.Not())
},
)
}

View File

@@ -0,0 +1,151 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"encoding/json"
"net/http"
"net/url"
"github.com/facebookincubator/ent/dialect/sql"
"github.com/facebookincubator/ent/entc/integration/json/ent/user"
)
// UserCreate is the builder for creating a User entity.
type UserCreate struct {
config
url **url.URL
raw *json.RawMessage
dirs *[]http.Dir
ints *[]int
floats *[]float64
strings *[]string
}
// SetURL sets the url field.
func (uc *UserCreate) SetURL(u *url.URL) *UserCreate {
uc.url = &u
return uc
}
// SetRaw sets the raw field.
func (uc *UserCreate) SetRaw(jm json.RawMessage) *UserCreate {
uc.raw = &jm
return uc
}
// SetDirs sets the dirs field.
func (uc *UserCreate) SetDirs(h []http.Dir) *UserCreate {
uc.dirs = &h
return uc
}
// SetInts sets the ints field.
func (uc *UserCreate) SetInts(i []int) *UserCreate {
uc.ints = &i
return uc
}
// SetFloats sets the floats field.
func (uc *UserCreate) SetFloats(f []float64) *UserCreate {
uc.floats = &f
return uc
}
// SetStrings sets the strings field.
func (uc *UserCreate) SetStrings(s []string) *UserCreate {
uc.strings = &s
return uc
}
// Save creates the User in the database.
func (uc *UserCreate) Save(ctx context.Context) (*User, error) {
return uc.sqlSave(ctx)
}
// SaveX calls Save and panics if Save returns an error.
func (uc *UserCreate) SaveX(ctx context.Context) *User {
v, err := uc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
func (uc *UserCreate) sqlSave(ctx context.Context) (*User, error) {
var (
res sql.Result
u = &User{config: uc.config}
)
tx, err := uc.driver.Tx(ctx)
if err != nil {
return nil, err
}
builder := sql.Insert(user.Table).Default(uc.driver.Dialect())
if value := uc.url; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return nil, err
}
builder.Set(user.FieldURL, buf)
u.URL = *value
}
if value := uc.raw; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return nil, err
}
builder.Set(user.FieldRaw, buf)
u.Raw = *value
}
if value := uc.dirs; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return nil, err
}
builder.Set(user.FieldDirs, buf)
u.Dirs = *value
}
if value := uc.ints; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return nil, err
}
builder.Set(user.FieldInts, buf)
u.Ints = *value
}
if value := uc.floats; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return nil, err
}
builder.Set(user.FieldFloats, buf)
u.Floats = *value
}
if value := uc.strings; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return nil, err
}
builder.Set(user.FieldStrings, buf)
u.Strings = *value
}
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)
}
u.ID = int(id)
if err := tx.Commit(); err != nil {
return nil, err
}
return u, nil
}

View File

@@ -0,0 +1,81 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"github.com/facebookincubator/ent/dialect/sql"
"github.com/facebookincubator/ent/entc/integration/json/ent/predicate"
"github.com/facebookincubator/ent/entc/integration/json/ent/user"
)
// UserDelete is the builder for deleting a User entity.
type UserDelete struct {
config
predicates []predicate.User
}
// Where adds a new predicate to the delete builder.
func (ud *UserDelete) Where(ps ...predicate.User) *UserDelete {
ud.predicates = append(ud.predicates, ps...)
return ud
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (ud *UserDelete) Exec(ctx context.Context) (int, error) {
return ud.sqlExec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (ud *UserDelete) ExecX(ctx context.Context) int {
n, err := ud.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (ud *UserDelete) sqlExec(ctx context.Context) (int, error) {
var res sql.Result
selector := sql.Select().From(sql.Table(user.Table))
for _, p := range ud.predicates {
p(selector)
}
query, args := sql.Delete(user.Table).FromSelect(selector).Query()
if err := ud.driver.Exec(ctx, query, args, &res); err != nil {
return 0, err
}
affected, err := res.RowsAffected()
if err != nil {
return 0, err
}
return int(affected), nil
}
// UserDeleteOne is the builder for deleting a single User entity.
type UserDeleteOne struct {
ud *UserDelete
}
// Exec executes the deletion query.
func (udo *UserDeleteOne) Exec(ctx context.Context) error {
n, err := udo.ud.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &ErrNotFound{user.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (udo *UserDeleteOne) ExecX(ctx context.Context) {
udo.ud.ExecX(ctx)
}

View File

@@ -0,0 +1,596 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"math"
"github.com/facebookincubator/ent/dialect/sql"
"github.com/facebookincubator/ent/entc/integration/json/ent/predicate"
"github.com/facebookincubator/ent/entc/integration/json/ent/user"
)
// UserQuery is the builder for querying User entities.
type UserQuery struct {
config
limit *int
offset *int
order []Order
unique []string
predicates []predicate.User
// intermediate queries.
sql *sql.Selector
}
// Where adds a new predicate for the builder.
func (uq *UserQuery) Where(ps ...predicate.User) *UserQuery {
uq.predicates = append(uq.predicates, ps...)
return uq
}
// Limit adds a limit step to the query.
func (uq *UserQuery) Limit(limit int) *UserQuery {
uq.limit = &limit
return uq
}
// Offset adds an offset step to the query.
func (uq *UserQuery) Offset(offset int) *UserQuery {
uq.offset = &offset
return uq
}
// Order adds an order step to the query.
func (uq *UserQuery) Order(o ...Order) *UserQuery {
uq.order = append(uq.order, o...)
return uq
}
// First returns the first User entity in the query. Returns *ErrNotFound when no user was found.
func (uq *UserQuery) First(ctx context.Context) (*User, error) {
us, err := uq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(us) == 0 {
return nil, &ErrNotFound{user.Label}
}
return us[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (uq *UserQuery) FirstX(ctx context.Context) *User {
u, err := uq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return u
}
// FirstID returns the first User id in the query. Returns *ErrNotFound when no id was found.
func (uq *UserQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = uq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &ErrNotFound{user.Label}
return
}
return ids[0], nil
}
// FirstXID is like FirstID, but panics if an error occurs.
func (uq *UserQuery) FirstXID(ctx context.Context) int {
id, err := uq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns the only User entity in the query, returns an error if not exactly one entity was returned.
func (uq *UserQuery) Only(ctx context.Context) (*User, error) {
us, err := uq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(us) {
case 1:
return us[0], nil
case 0:
return nil, &ErrNotFound{user.Label}
default:
return nil, &ErrNotSingular{user.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (uq *UserQuery) OnlyX(ctx context.Context) *User {
u, err := uq.Only(ctx)
if err != nil {
panic(err)
}
return u
}
// OnlyID returns the only User id in the query, returns an error if not exactly one id was returned.
func (uq *UserQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = uq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &ErrNotFound{user.Label}
default:
err = &ErrNotSingular{user.Label}
}
return
}
// OnlyXID is like OnlyID, but panics if an error occurs.
func (uq *UserQuery) OnlyXID(ctx context.Context) int {
id, err := uq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Users.
func (uq *UserQuery) All(ctx context.Context) ([]*User, error) {
return uq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (uq *UserQuery) AllX(ctx context.Context) []*User {
us, err := uq.All(ctx)
if err != nil {
panic(err)
}
return us
}
// IDs executes the query and returns a list of User ids.
func (uq *UserQuery) IDs(ctx context.Context) ([]int, error) {
return uq.sqlIDs(ctx)
}
// IDsX is like IDs, but panics if an error occurs.
func (uq *UserQuery) IDsX(ctx context.Context) []int {
ids, err := uq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (uq *UserQuery) Count(ctx context.Context) (int, error) {
return uq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (uq *UserQuery) CountX(ctx context.Context) int {
count, err := uq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (uq *UserQuery) Exist(ctx context.Context) (bool, error) {
return uq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (uq *UserQuery) ExistX(ctx context.Context) bool {
exist, err := uq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the 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 (uq *UserQuery) Clone() *UserQuery {
return &UserQuery{
config: uq.config,
limit: uq.limit,
offset: uq.offset,
order: append([]Order{}, uq.order...),
unique: append([]string{}, uq.unique...),
predicates: append([]predicate.User{}, uq.predicates...),
// clone intermediate queries.
sql: uq.sql.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.
//
// Example:
//
// var v []struct {
// URL *url.URL `json:"url,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.User.Query().
// GroupBy(user.FieldURL).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
//
func (uq *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy {
group := &UserGroupBy{config: uq.config}
group.fields = append([]string{field}, fields...)
group.sql = uq.sqlQuery()
return group
}
// Select one or more fields from the given query.
//
// Example:
//
// var v []struct {
// URL *url.URL `json:"url,omitempty"`
// }
//
// client.User.Query().
// Select(user.FieldURL).
// Scan(ctx, &v)
//
func (uq *UserQuery) Select(field string, fields ...string) *UserSelect {
selector := &UserSelect{config: uq.config}
selector.fields = append([]string{field}, fields...)
selector.sql = uq.sqlQuery()
return selector
}
func (uq *UserQuery) sqlAll(ctx context.Context) ([]*User, error) {
rows := &sql.Rows{}
selector := uq.sqlQuery()
if unique := uq.unique; len(unique) == 0 {
selector.Distinct()
}
query, args := selector.Query()
if err := uq.driver.Query(ctx, query, args, rows); err != nil {
return nil, err
}
defer rows.Close()
var us Users
if err := us.FromRows(rows); err != nil {
return nil, err
}
us.config(uq.config)
return us, nil
}
func (uq *UserQuery) sqlCount(ctx context.Context) (int, error) {
rows := &sql.Rows{}
selector := uq.sqlQuery()
unique := []string{user.FieldID}
if len(uq.unique) > 0 {
unique = uq.unique
}
selector.Count(sql.Distinct(selector.Columns(unique...)...))
query, args := selector.Query()
if err := uq.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 (uq *UserQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := uq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("ent: check existence: %v", err)
}
return n > 0, nil
}
func (uq *UserQuery) sqlIDs(ctx context.Context) ([]int, error) {
vs, err := uq.sqlAll(ctx)
if err != nil {
return nil, err
}
var ids []int
for _, v := range vs {
ids = append(ids, v.ID)
}
return ids, nil
}
func (uq *UserQuery) sqlQuery() *sql.Selector {
t1 := sql.Table(user.Table)
selector := sql.Select(t1.Columns(user.Columns...)...).From(t1)
if uq.sql != nil {
selector = uq.sql
selector.Select(selector.Columns(user.Columns...)...)
}
for _, p := range uq.predicates {
p(selector)
}
for _, p := range uq.order {
p(selector)
}
if offset := uq.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 := uq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// UserGroupBy is the builder for group-by User entities.
type UserGroupBy struct {
config
fields []string
fns []Aggregate
// intermediate queries.
sql *sql.Selector
}
// Aggregate adds the given aggregation functions to the group-by query.
func (ugb *UserGroupBy) Aggregate(fns ...Aggregate) *UserGroupBy {
ugb.fns = append(ugb.fns, fns...)
return ugb
}
// Scan applies the group-by query and scan the result into the given value.
func (ugb *UserGroupBy) Scan(ctx context.Context, v interface{}) error {
return ugb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (ugb *UserGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := ugb.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 (ugb *UserGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(ugb.fields) > 1 {
return nil, errors.New("ent: UserGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := ugb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (ugb *UserGroupBy) StringsX(ctx context.Context) []string {
v, err := ugb.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 (ugb *UserGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(ugb.fields) > 1 {
return nil, errors.New("ent: UserGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := ugb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (ugb *UserGroupBy) IntsX(ctx context.Context) []int {
v, err := ugb.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 (ugb *UserGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(ugb.fields) > 1 {
return nil, errors.New("ent: UserGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := ugb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (ugb *UserGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := ugb.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 (ugb *UserGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(ugb.fields) > 1 {
return nil, errors.New("ent: UserGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := ugb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (ugb *UserGroupBy) BoolsX(ctx context.Context) []bool {
v, err := ugb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
func (ugb *UserGroupBy) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := ugb.sqlQuery().Query()
if err := ugb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (ugb *UserGroupBy) sqlQuery() *sql.Selector {
selector := ugb.sql
columns := make([]string, 0, len(ugb.fields)+len(ugb.fns))
columns = append(columns, ugb.fields...)
for _, fn := range ugb.fns {
columns = append(columns, fn.SQL(selector))
}
return selector.Select(columns...).GroupBy(ugb.fields...)
}
// UserSelect is the builder for select fields of User entities.
type UserSelect struct {
config
fields []string
// intermediate queries.
sql *sql.Selector
}
// Scan applies the selector query and scan the result into the given value.
func (us *UserSelect) Scan(ctx context.Context, v interface{}) error {
return us.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (us *UserSelect) ScanX(ctx context.Context, v interface{}) {
if err := us.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from selector. It is only allowed when selecting one field.
func (us *UserSelect) Strings(ctx context.Context) ([]string, error) {
if len(us.fields) > 1 {
return nil, errors.New("ent: UserSelect.Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := us.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (us *UserSelect) StringsX(ctx context.Context) []string {
v, err := us.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from selector. It is only allowed when selecting one field.
func (us *UserSelect) Ints(ctx context.Context) ([]int, error) {
if len(us.fields) > 1 {
return nil, errors.New("ent: UserSelect.Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := us.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (us *UserSelect) IntsX(ctx context.Context) []int {
v, err := us.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from selector. It is only allowed when selecting one field.
func (us *UserSelect) Float64s(ctx context.Context) ([]float64, error) {
if len(us.fields) > 1 {
return nil, errors.New("ent: UserSelect.Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := us.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (us *UserSelect) Float64sX(ctx context.Context) []float64 {
v, err := us.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from selector. It is only allowed when selecting one field.
func (us *UserSelect) Bools(ctx context.Context) ([]bool, error) {
if len(us.fields) > 1 {
return nil, errors.New("ent: UserSelect.Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := us.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (us *UserSelect) BoolsX(ctx context.Context) []bool {
v, err := us.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
func (us *UserSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := us.sqlQuery().Query()
if err := us.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (us *UserSelect) sqlQuery() sql.Querier {
view := "user_view"
return sql.Select(us.fields...).From(us.sql.As(view))
}

View File

@@ -0,0 +1,498 @@
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Code generated (@generated) by entc, DO NOT EDIT.
package ent
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"github.com/facebookincubator/ent/dialect/sql"
"github.com/facebookincubator/ent/entc/integration/json/ent/predicate"
"github.com/facebookincubator/ent/entc/integration/json/ent/user"
)
// UserUpdate is the builder for updating User entities.
type UserUpdate struct {
config
url **url.URL
clearurl bool
raw *json.RawMessage
clearraw bool
dirs *[]http.Dir
cleardirs bool
ints *[]int
clearints bool
floats *[]float64
clearfloats bool
strings *[]string
clearstrings bool
predicates []predicate.User
}
// Where adds a new predicate for the builder.
func (uu *UserUpdate) Where(ps ...predicate.User) *UserUpdate {
uu.predicates = append(uu.predicates, ps...)
return uu
}
// SetURL sets the url field.
func (uu *UserUpdate) SetURL(u *url.URL) *UserUpdate {
uu.url = &u
return uu
}
// ClearURL clears the value of url.
func (uu *UserUpdate) ClearURL() *UserUpdate {
uu.url = nil
uu.clearurl = true
return uu
}
// SetRaw sets the raw field.
func (uu *UserUpdate) SetRaw(jm json.RawMessage) *UserUpdate {
uu.raw = &jm
return uu
}
// ClearRaw clears the value of raw.
func (uu *UserUpdate) ClearRaw() *UserUpdate {
uu.raw = nil
uu.clearraw = true
return uu
}
// SetDirs sets the dirs field.
func (uu *UserUpdate) SetDirs(h []http.Dir) *UserUpdate {
uu.dirs = &h
return uu
}
// ClearDirs clears the value of dirs.
func (uu *UserUpdate) ClearDirs() *UserUpdate {
uu.dirs = nil
uu.cleardirs = true
return uu
}
// SetInts sets the ints field.
func (uu *UserUpdate) SetInts(i []int) *UserUpdate {
uu.ints = &i
return uu
}
// ClearInts clears the value of ints.
func (uu *UserUpdate) ClearInts() *UserUpdate {
uu.ints = nil
uu.clearints = true
return uu
}
// SetFloats sets the floats field.
func (uu *UserUpdate) SetFloats(f []float64) *UserUpdate {
uu.floats = &f
return uu
}
// ClearFloats clears the value of floats.
func (uu *UserUpdate) ClearFloats() *UserUpdate {
uu.floats = nil
uu.clearfloats = true
return uu
}
// SetStrings sets the strings field.
func (uu *UserUpdate) SetStrings(s []string) *UserUpdate {
uu.strings = &s
return uu
}
// ClearStrings clears the value of strings.
func (uu *UserUpdate) ClearStrings() *UserUpdate {
uu.strings = nil
uu.clearstrings = true
return uu
}
// Save executes the query and returns the number of rows/vertices matched by this operation.
func (uu *UserUpdate) Save(ctx context.Context) (int, error) {
return uu.sqlSave(ctx)
}
// SaveX is like Save, but panics if an error occurs.
func (uu *UserUpdate) SaveX(ctx context.Context) int {
affected, err := uu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (uu *UserUpdate) Exec(ctx context.Context) error {
_, err := uu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (uu *UserUpdate) ExecX(ctx context.Context) {
if err := uu.Exec(ctx); err != nil {
panic(err)
}
}
func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) {
selector := sql.Select(user.FieldID).From(sql.Table(user.Table))
for _, p := range uu.predicates {
p(selector)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err = uu.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 := uu.driver.Tx(ctx)
if err != nil {
return 0, err
}
var (
res sql.Result
builder = sql.Update(user.Table).Where(sql.InInts(user.FieldID, ids...))
)
if value := uu.url; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return 0, err
}
builder.Set(user.FieldURL, buf)
}
if uu.clearurl {
builder.SetNull(user.FieldURL)
}
if value := uu.raw; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return 0, err
}
builder.Set(user.FieldRaw, buf)
}
if uu.clearraw {
builder.SetNull(user.FieldRaw)
}
if value := uu.dirs; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return 0, err
}
builder.Set(user.FieldDirs, buf)
}
if uu.cleardirs {
builder.SetNull(user.FieldDirs)
}
if value := uu.ints; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return 0, err
}
builder.Set(user.FieldInts, buf)
}
if uu.clearints {
builder.SetNull(user.FieldInts)
}
if value := uu.floats; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return 0, err
}
builder.Set(user.FieldFloats, buf)
}
if uu.clearfloats {
builder.SetNull(user.FieldFloats)
}
if value := uu.strings; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return 0, err
}
builder.Set(user.FieldStrings, buf)
}
if uu.clearstrings {
builder.SetNull(user.FieldStrings)
}
if !builder.Empty() {
query, args := builder.Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return 0, rollback(tx, err)
}
}
if err = tx.Commit(); err != nil {
return 0, err
}
return len(ids), nil
}
// UserUpdateOne is the builder for updating a single User entity.
type UserUpdateOne struct {
config
id int
url **url.URL
clearurl bool
raw *json.RawMessage
clearraw bool
dirs *[]http.Dir
cleardirs bool
ints *[]int
clearints bool
floats *[]float64
clearfloats bool
strings *[]string
clearstrings bool
}
// SetURL sets the url field.
func (uuo *UserUpdateOne) SetURL(u *url.URL) *UserUpdateOne {
uuo.url = &u
return uuo
}
// ClearURL clears the value of url.
func (uuo *UserUpdateOne) ClearURL() *UserUpdateOne {
uuo.url = nil
uuo.clearurl = true
return uuo
}
// SetRaw sets the raw field.
func (uuo *UserUpdateOne) SetRaw(jm json.RawMessage) *UserUpdateOne {
uuo.raw = &jm
return uuo
}
// ClearRaw clears the value of raw.
func (uuo *UserUpdateOne) ClearRaw() *UserUpdateOne {
uuo.raw = nil
uuo.clearraw = true
return uuo
}
// SetDirs sets the dirs field.
func (uuo *UserUpdateOne) SetDirs(h []http.Dir) *UserUpdateOne {
uuo.dirs = &h
return uuo
}
// ClearDirs clears the value of dirs.
func (uuo *UserUpdateOne) ClearDirs() *UserUpdateOne {
uuo.dirs = nil
uuo.cleardirs = true
return uuo
}
// SetInts sets the ints field.
func (uuo *UserUpdateOne) SetInts(i []int) *UserUpdateOne {
uuo.ints = &i
return uuo
}
// ClearInts clears the value of ints.
func (uuo *UserUpdateOne) ClearInts() *UserUpdateOne {
uuo.ints = nil
uuo.clearints = true
return uuo
}
// SetFloats sets the floats field.
func (uuo *UserUpdateOne) SetFloats(f []float64) *UserUpdateOne {
uuo.floats = &f
return uuo
}
// ClearFloats clears the value of floats.
func (uuo *UserUpdateOne) ClearFloats() *UserUpdateOne {
uuo.floats = nil
uuo.clearfloats = true
return uuo
}
// SetStrings sets the strings field.
func (uuo *UserUpdateOne) SetStrings(s []string) *UserUpdateOne {
uuo.strings = &s
return uuo
}
// ClearStrings clears the value of strings.
func (uuo *UserUpdateOne) ClearStrings() *UserUpdateOne {
uuo.strings = nil
uuo.clearstrings = true
return uuo
}
// Save executes the query and returns the updated entity.
func (uuo *UserUpdateOne) Save(ctx context.Context) (*User, error) {
return uuo.sqlSave(ctx)
}
// SaveX is like Save, but panics if an error occurs.
func (uuo *UserUpdateOne) SaveX(ctx context.Context) *User {
u, err := uuo.Save(ctx)
if err != nil {
panic(err)
}
return u
}
// Exec executes the query on the entity.
func (uuo *UserUpdateOne) Exec(ctx context.Context) error {
_, err := uuo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (uuo *UserUpdateOne) ExecX(ctx context.Context) {
if err := uuo.Exec(ctx); err != nil {
panic(err)
}
}
func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (u *User, err error) {
selector := sql.Select(user.Columns...).From(sql.Table(user.Table))
user.ID(uuo.id)(selector)
rows := &sql.Rows{}
query, args := selector.Query()
if err = uuo.driver.Query(ctx, query, args, rows); err != nil {
return nil, err
}
defer rows.Close()
var ids []int
for rows.Next() {
var id int
u = &User{config: uuo.config}
if err := u.FromRows(rows); err != nil {
return nil, fmt.Errorf("ent: failed scanning row into User: %v", err)
}
id = u.ID
ids = append(ids, id)
}
switch n := len(ids); {
case n == 0:
return nil, fmt.Errorf("ent: User not found with id: %v", uuo.id)
case n > 1:
return nil, fmt.Errorf("ent: more than one User with the same id: %v", uuo.id)
}
tx, err := uuo.driver.Tx(ctx)
if err != nil {
return nil, err
}
var (
res sql.Result
builder = sql.Update(user.Table).Where(sql.InInts(user.FieldID, ids...))
)
if value := uuo.url; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return nil, err
}
builder.Set(user.FieldURL, buf)
u.URL = *value
}
if uuo.clearurl {
var value *url.URL
u.URL = value
builder.SetNull(user.FieldURL)
}
if value := uuo.raw; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return nil, err
}
builder.Set(user.FieldRaw, buf)
u.Raw = *value
}
if uuo.clearraw {
var value json.RawMessage
u.Raw = value
builder.SetNull(user.FieldRaw)
}
if value := uuo.dirs; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return nil, err
}
builder.Set(user.FieldDirs, buf)
u.Dirs = *value
}
if uuo.cleardirs {
var value []http.Dir
u.Dirs = value
builder.SetNull(user.FieldDirs)
}
if value := uuo.ints; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return nil, err
}
builder.Set(user.FieldInts, buf)
u.Ints = *value
}
if uuo.clearints {
var value []int
u.Ints = value
builder.SetNull(user.FieldInts)
}
if value := uuo.floats; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return nil, err
}
builder.Set(user.FieldFloats, buf)
u.Floats = *value
}
if uuo.clearfloats {
var value []float64
u.Floats = value
builder.SetNull(user.FieldFloats)
}
if value := uuo.strings; value != nil {
buf, err := json.Marshal(*value)
if err != nil {
return nil, err
}
builder.Set(user.FieldStrings, buf)
u.Strings = *value
}
if uuo.clearstrings {
var value []string
u.Strings = value
builder.SetNull(user.FieldStrings)
}
if !builder.Empty() {
query, args := builder.Query()
if err := tx.Exec(ctx, query, args, &res); err != nil {
return nil, rollback(tx, err)
}
}
if err = tx.Commit(); err != nil {
return nil, err
}
return u, nil
}

View File

@@ -0,0 +1,114 @@
package json
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"testing"
"github.com/facebookincubator/ent/entc/integration/json/ent"
"github.com/facebookincubator/ent/entc/integration/json/ent/migrate"
"github.com/facebookincubator/ent/entc/integration/json/ent/user"
"github.com/facebookincubator/ent/dialect/sql"
_ "github.com/go-sql-driver/mysql"
"github.com/stretchr/testify/require"
)
func TestMySQL(t *testing.T) {
for version, port := range map[string]int{"56": 3306, "57": 3307, "8": 3308} {
t.Run(version, func(t *testing.T) {
root, err := sql.Open("mysql", fmt.Sprintf("root:pass@tcp(localhost:%d)/", port))
require.NoError(t, err)
defer root.Close()
ctx := context.Background()
err = root.Exec(ctx, "CREATE DATABASE IF NOT EXISTS json", []interface{}{}, new(sql.Result))
require.NoError(t, err, "creating database")
defer root.Exec(ctx, "DROP DATABASE IF EXISTS json", []interface{}{}, new(sql.Result))
drv, err := sql.Open("mysql", fmt.Sprintf("root:pass@tcp(localhost:%d)/json?parseTime=True", port))
require.NoError(t, err, "connecting to migrate database")
client := ent.NewClient(ent.Driver(drv))
require.NoError(t, client.Schema.Create(ctx, migrate.WithGlobalUniqueID(true)))
URL(t, client)
Dirs(t, client)
Ints(t, client)
Floats(t, client)
Strings(t, client)
RawMessage(t, client)
})
}
}
func Ints(t *testing.T, client *ent.Client) {
ctx := context.Background()
ints := []int{1, 2, 3}
usr := client.User.Create().SetInts(ints).SaveX(ctx)
require.Equal(t, ints, usr.Ints)
require.Equal(t, ints, client.User.GetX(ctx, usr.ID).Ints)
usr = usr.Update().SetInts(ints[:1]).SaveX(ctx)
require.Equal(t, ints[:1], usr.Ints)
require.Equal(t, ints[:1], client.User.GetX(ctx, usr.ID).Ints)
usr = usr.Update().ClearInts().SaveX(ctx)
require.Empty(t, usr.Ints)
require.Empty(t, client.User.GetX(ctx, usr.ID).Ints)
}
func Floats(t *testing.T, client *ent.Client) {
ctx := context.Background()
flts := []float64{1, 2, 3}
usr := client.User.Create().SetFloats(flts).SaveX(ctx)
require.Equal(t, flts, usr.Floats)
require.Equal(t, flts, client.User.GetX(ctx, usr.ID).Floats)
usr = usr.Update().SetFloats(flts[:1]).SaveX(ctx)
require.Equal(t, flts[:1], usr.Floats)
require.Equal(t, flts[:1], client.User.GetX(ctx, usr.ID).Floats)
usr = usr.Update().ClearFloats().SaveX(ctx)
require.Empty(t, usr.Floats)
require.Empty(t, client.User.GetX(ctx, usr.ID).Floats)
}
func Strings(t *testing.T, client *ent.Client) {
ctx := context.Background()
str := []string{"a", "b", "c"}
usr := client.User.Create().SetStrings(str).SaveX(ctx)
require.Equal(t, str, usr.Strings)
require.Equal(t, str, client.User.GetX(ctx, usr.ID).Strings)
usr = usr.Update().SetStrings(str[:1]).SaveX(ctx)
require.Equal(t, str[:1], usr.Strings)
require.Equal(t, str[:1], client.User.GetX(ctx, usr.ID).Strings)
require.Equal(t, 1, client.User.Query().Where(user.StringsNotNil()).CountX(ctx))
usr = usr.Update().ClearStrings().SaveX(ctx)
require.Empty(t, usr.Strings)
require.Empty(t, client.User.GetX(ctx, usr.ID).Strings)
require.Zero(t, client.User.Query().Where(user.StringsNotNil()).CountX(ctx))
}
func RawMessage(t *testing.T, client *ent.Client) {
ctx := context.Background()
raw := json.RawMessage("{}")
usr := client.User.Create().SetRaw(raw).SaveX(ctx)
require.Equal(t, raw, usr.Raw)
require.Equal(t, raw, client.User.GetX(ctx, usr.ID).Raw)
}
func Dirs(t *testing.T, client *ent.Client) {
ctx := context.Background()
dirs := []http.Dir{"dev", "usr"}
usr := client.User.Create().SetDirs(dirs).SaveX(ctx)
require.Equal(t, dirs, usr.Dirs)
require.Equal(t, dirs, client.User.GetX(ctx, usr.ID).Dirs)
}
func URL(t *testing.T, client *ent.Client) {
ctx := context.Background()
u, err := url.Parse("https://github.com/a8m")
require.NoError(t, err)
usr := client.User.Create().SetURL(u).SaveX(ctx)
require.Equal(t, u, usr.URL)
require.Equal(t, u, client.User.GetX(ctx, usr.ID).URL)
}