mirror of
https://github.com/ent/ent.git
synced 2026-05-22 09:31:45 +03:00
entc/gen: derive the id-type from the schema (#823)
if it was not provided
This commit is contained in:
@@ -17,7 +17,6 @@ import (
|
||||
|
||||
"github.com/facebook/ent/entc/gen"
|
||||
"github.com/facebook/ent/entc/load"
|
||||
"github.com/facebook/ent/schema/field"
|
||||
)
|
||||
|
||||
// LoadGraph loads the schema package from the given schema path,
|
||||
@@ -58,9 +57,6 @@ func Generate(schemaPath string, cfg *gen.Config, options ...Option) (err error)
|
||||
// the schema.
|
||||
cfg.Target = filepath.Dir(abs)
|
||||
}
|
||||
if cfg.IDType == nil {
|
||||
cfg.IDType = &field.TypeInfo{Type: field.TypeInt}
|
||||
}
|
||||
for _, opt := range options {
|
||||
if err := opt(cfg); err != nil {
|
||||
return err
|
||||
|
||||
@@ -98,9 +98,35 @@ func NewGraph(c *Config, schemas ...*load.Schema) (g *Graph, err error) {
|
||||
for i := range schemas {
|
||||
g.addIndexes(schemas[i])
|
||||
}
|
||||
g.defaults()
|
||||
return
|
||||
}
|
||||
|
||||
// defaultIDType holds the default value for IDType.
|
||||
var defaultIDType = &field.TypeInfo{Type: field.TypeInt}
|
||||
|
||||
// defaults sets the default value of the IDType. The IDType field is used
|
||||
// by multiple templates. If the IDType wasn't provided, it will fallback to
|
||||
// int, or the one used in the schema (if all schemas share the same IDType).
|
||||
func (g *Graph) defaults() {
|
||||
if g.IDType != nil {
|
||||
return
|
||||
}
|
||||
if len(g.Nodes) == 0 {
|
||||
g.IDType = defaultIDType
|
||||
return
|
||||
}
|
||||
// Check that all nodes have the same type for the ID field.
|
||||
for i := 0; i < len(g.Nodes)-1; i++ {
|
||||
cid, nid := g.Nodes[i].ID.Type, g.Nodes[i+1].ID.Type
|
||||
if cid.Type != nid.Type {
|
||||
g.IDType = defaultIDType
|
||||
return
|
||||
}
|
||||
}
|
||||
g.IDType = g.Nodes[0].ID.Type
|
||||
}
|
||||
|
||||
// Gen generates the artifacts for the graph.
|
||||
func (g *Graph) Gen() error {
|
||||
var (
|
||||
|
||||
@@ -160,11 +160,15 @@ type (
|
||||
|
||||
// NewType creates a new type and its fields from the given schema.
|
||||
func NewType(c *Config, schema *load.Schema) (*Type, error) {
|
||||
idType := c.IDType
|
||||
if idType == nil {
|
||||
idType = defaultIDType
|
||||
}
|
||||
typ := &Type{
|
||||
Config: c,
|
||||
ID: &Field{
|
||||
Name: "id",
|
||||
Type: c.IDType,
|
||||
Type: idType,
|
||||
StructTag: structTag("id", ""),
|
||||
},
|
||||
schema: schema,
|
||||
|
||||
Reference in New Issue
Block a user