Further progress on sqlite

This commit is contained in:
Matthew Kilgore
2025-09-05 22:44:40 -04:00
parent 8f4ed9afd2
commit e7f5866465
13 changed files with 774 additions and 566 deletions

View File

@@ -901,22 +901,6 @@ func (c *EntityClient) QueryGroup(_m *Entity) *GroupQuery {
return query
}
// QueryParent queries the parent edge of a Entity.
func (c *EntityClient) QueryParent(_m *Entity) *EntityQuery {
query := (&EntityClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(entity.Table, entity.FieldID, id),
sqlgraph.To(entity.Table, entity.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, entity.ParentTable, entity.ParentColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryChildren queries the children edge of a Entity.
func (c *EntityClient) QueryChildren(_m *Entity) *EntityQuery {
query := (&EntityClient{config: c.config}).Query()
@@ -925,7 +909,23 @@ func (c *EntityClient) QueryChildren(_m *Entity) *EntityQuery {
step := sqlgraph.NewStep(
sqlgraph.From(entity.Table, entity.FieldID, id),
sqlgraph.To(entity.Table, entity.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, entity.ChildrenTable, entity.ChildrenColumn),
sqlgraph.Edge(sqlgraph.O2M, true, entity.ChildrenTable, entity.ChildrenColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryParent queries the parent edge of a Entity.
func (c *EntityClient) QueryParent(_m *Entity) *EntityQuery {
query := (&EntityClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(entity.Table, entity.FieldID, id),
sqlgraph.To(entity.Table, entity.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, entity.ParentTable, entity.ParentColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
@@ -941,7 +941,7 @@ func (c *EntityClient) QueryEntity(_m *Entity) *EntityQuery {
step := sqlgraph.NewStep(
sqlgraph.From(entity.Table, entity.FieldID, id),
sqlgraph.To(entity.Table, entity.FieldID),
sqlgraph.Edge(sqlgraph.O2O, true, entity.EntityTable, entity.EntityColumn),
sqlgraph.Edge(sqlgraph.O2M, true, entity.EntityTable, entity.EntityColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
@@ -957,7 +957,7 @@ func (c *EntityClient) QueryLocation(_m *Entity) *EntityQuery {
step := sqlgraph.NewStep(
sqlgraph.From(entity.Table, entity.FieldID, id),
sqlgraph.To(entity.Table, entity.FieldID),
sqlgraph.Edge(sqlgraph.O2O, false, entity.LocationTable, entity.LocationColumn),
sqlgraph.Edge(sqlgraph.M2O, false, entity.LocationTable, entity.LocationColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil

View File

@@ -71,7 +71,7 @@ type Entity struct {
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the EntityQuery when eager-loading is set.
Edges EntityEdges `json:"edges"`
entity_children *uuid.UUID
entity_parent *uuid.UUID
entity_location *uuid.UUID
entity_type_entities *uuid.UUID
group_entities *uuid.UUID
@@ -82,12 +82,12 @@ type Entity struct {
type EntityEdges struct {
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// Parent holds the value of the parent edge.
Parent *Entity `json:"parent,omitempty"`
// Children holds the value of the children edge.
Children []*Entity `json:"children,omitempty"`
// Parent holds the value of the parent edge.
Parent *Entity `json:"parent,omitempty"`
// Entity holds the value of the entity edge.
Entity *Entity `json:"entity,omitempty"`
Entity []*Entity `json:"entity,omitempty"`
// Location holds the value of the location edge.
Location *Entity `json:"location,omitempty"`
// Label holds the value of the label edge.
@@ -116,34 +116,32 @@ func (e EntityEdges) GroupOrErr() (*Group, error) {
return nil, &NotLoadedError{edge: "group"}
}
// ParentOrErr returns the Parent value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e EntityEdges) ParentOrErr() (*Entity, error) {
if e.Parent != nil {
return e.Parent, nil
} else if e.loadedTypes[1] {
return nil, &NotFoundError{label: entity.Label}
}
return nil, &NotLoadedError{edge: "parent"}
}
// ChildrenOrErr returns the Children value or an error if the edge
// was not loaded in eager-loading.
func (e EntityEdges) ChildrenOrErr() ([]*Entity, error) {
if e.loadedTypes[2] {
if e.loadedTypes[1] {
return e.Children, nil
}
return nil, &NotLoadedError{edge: "children"}
}
// EntityOrErr returns the Entity value or an error if the edge
// ParentOrErr returns the Parent value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e EntityEdges) EntityOrErr() (*Entity, error) {
if e.Entity != nil {
return e.Entity, nil
} else if e.loadedTypes[3] {
func (e EntityEdges) ParentOrErr() (*Entity, error) {
if e.Parent != nil {
return e.Parent, nil
} else if e.loadedTypes[2] {
return nil, &NotFoundError{label: entity.Label}
}
return nil, &NotLoadedError{edge: "parent"}
}
// EntityOrErr returns the Entity value or an error if the edge
// was not loaded in eager-loading.
func (e EntityEdges) EntityOrErr() ([]*Entity, error) {
if e.loadedTypes[3] {
return e.Entity, nil
}
return nil, &NotLoadedError{edge: "entity"}
}
@@ -222,7 +220,7 @@ func (*Entity) scanValues(columns []string) ([]any, error) {
values[i] = new(sql.NullTime)
case entity.FieldID:
values[i] = new(uuid.UUID)
case entity.ForeignKeys[0]: // entity_children
case entity.ForeignKeys[0]: // entity_parent
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
case entity.ForeignKeys[1]: // entity_location
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
@@ -397,10 +395,10 @@ func (_m *Entity) assignValues(columns []string, values []any) error {
}
case entity.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field entity_children", values[i])
return fmt.Errorf("unexpected type %T for field entity_parent", values[i])
} else if value.Valid {
_m.entity_children = new(uuid.UUID)
*_m.entity_children = *value.S.(*uuid.UUID)
_m.entity_parent = new(uuid.UUID)
*_m.entity_parent = *value.S.(*uuid.UUID)
}
case entity.ForeignKeys[1]:
if value, ok := values[i].(*sql.NullScanner); !ok {
@@ -441,16 +439,16 @@ func (_m *Entity) QueryGroup() *GroupQuery {
return NewEntityClient(_m.config).QueryGroup(_m)
}
// QueryParent queries the "parent" edge of the Entity entity.
func (_m *Entity) QueryParent() *EntityQuery {
return NewEntityClient(_m.config).QueryParent(_m)
}
// QueryChildren queries the "children" edge of the Entity entity.
func (_m *Entity) QueryChildren() *EntityQuery {
return NewEntityClient(_m.config).QueryChildren(_m)
}
// QueryParent queries the "parent" edge of the Entity entity.
func (_m *Entity) QueryParent() *EntityQuery {
return NewEntityClient(_m.config).QueryParent(_m)
}
// QueryEntity queries the "entity" edge of the Entity entity.
func (_m *Entity) QueryEntity() *EntityQuery {
return NewEntityClient(_m.config).QueryEntity(_m)

View File

@@ -65,10 +65,10 @@ const (
FieldSoldNotes = "sold_notes"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// EdgeParent holds the string denoting the parent edge name in mutations.
EdgeParent = "parent"
// EdgeChildren holds the string denoting the children edge name in mutations.
EdgeChildren = "children"
// EdgeParent holds the string denoting the parent edge name in mutations.
EdgeParent = "parent"
// EdgeEntity holds the string denoting the entity edge name in mutations.
EdgeEntity = "entity"
// EdgeLocation holds the string denoting the location edge name in mutations.
@@ -92,14 +92,14 @@ const (
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "group_entities"
// ParentTable is the table that holds the parent relation/edge.
ParentTable = "entities"
// ParentColumn is the table column denoting the parent relation/edge.
ParentColumn = "entity_children"
// ChildrenTable is the table that holds the children relation/edge.
ChildrenTable = "entities"
// ChildrenColumn is the table column denoting the children relation/edge.
ChildrenColumn = "entity_children"
ChildrenColumn = "entity_parent"
// ParentTable is the table that holds the parent relation/edge.
ParentTable = "entities"
// ParentColumn is the table column denoting the parent relation/edge.
ParentColumn = "entity_parent"
// EntityTable is the table that holds the entity relation/edge.
EntityTable = "entities"
// EntityColumn is the table column denoting the entity relation/edge.
@@ -175,7 +175,7 @@ var Columns = []string{
// ForeignKeys holds the SQL foreign-keys that are owned by the "entities"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"entity_children",
"entity_parent",
"entity_location",
"entity_type_entities",
"group_entities",
@@ -382,13 +382,6 @@ func ByGroupField(field string, opts ...sql.OrderTermOption) OrderOption {
}
}
// ByParentField orders the results by parent field.
func ByParentField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newParentStep(), sql.OrderByField(field, opts...))
}
}
// ByChildrenCount orders the results by children count.
func ByChildrenCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
@@ -403,10 +396,24 @@ func ByChildren(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
}
}
// ByEntityField orders the results by entity field.
func ByEntityField(field string, opts ...sql.OrderTermOption) OrderOption {
// ByParentField orders the results by parent field.
func ByParentField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newEntityStep(), sql.OrderByField(field, opts...))
sqlgraph.OrderByNeighborTerms(s, newParentStep(), sql.OrderByField(field, opts...))
}
}
// ByEntityCount orders the results by entity count.
func ByEntityCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newEntityStep(), opts...)
}
}
// ByEntity orders the results by entity terms.
func ByEntity(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newEntityStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
@@ -486,32 +493,32 @@ func newGroupStep() *sqlgraph.Step {
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
}
func newParentStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, ParentTable, ParentColumn),
)
}
func newChildrenStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, ChildrenTable, ChildrenColumn),
sqlgraph.Edge(sqlgraph.O2M, true, ChildrenTable, ChildrenColumn),
)
}
func newParentStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, ParentTable, ParentColumn),
)
}
func newEntityStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2O, true, EntityTable, EntityColumn),
sqlgraph.Edge(sqlgraph.O2M, true, EntityTable, EntityColumn),
)
}
func newLocationStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2O, false, LocationTable, LocationColumn),
sqlgraph.Edge(sqlgraph.M2O, false, LocationTable, LocationColumn),
)
}
func newLabelStep() *sqlgraph.Step {

View File

@@ -1444,35 +1444,12 @@ func HasGroupWith(preds ...predicate.Group) predicate.Entity {
})
}
// HasParent applies the HasEdge predicate on the "parent" edge.
func HasParent() predicate.Entity {
return predicate.Entity(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, ParentTable, ParentColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasParentWith applies the HasEdge predicate on the "parent" edge with a given conditions (other predicates).
func HasParentWith(preds ...predicate.Entity) predicate.Entity {
return predicate.Entity(func(s *sql.Selector) {
step := newParentStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasChildren applies the HasEdge predicate on the "children" edge.
func HasChildren() predicate.Entity {
return predicate.Entity(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, ChildrenTable, ChildrenColumn),
sqlgraph.Edge(sqlgraph.O2M, true, ChildrenTable, ChildrenColumn),
)
sqlgraph.HasNeighbors(s, step)
})
@@ -1490,12 +1467,35 @@ func HasChildrenWith(preds ...predicate.Entity) predicate.Entity {
})
}
// HasParent applies the HasEdge predicate on the "parent" edge.
func HasParent() predicate.Entity {
return predicate.Entity(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, ParentTable, ParentColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasParentWith applies the HasEdge predicate on the "parent" edge with a given conditions (other predicates).
func HasParentWith(preds ...predicate.Entity) predicate.Entity {
return predicate.Entity(func(s *sql.Selector) {
step := newParentStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasEntity applies the HasEdge predicate on the "entity" edge.
func HasEntity() predicate.Entity {
return predicate.Entity(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2O, true, EntityTable, EntityColumn),
sqlgraph.Edge(sqlgraph.O2M, true, EntityTable, EntityColumn),
)
sqlgraph.HasNeighbors(s, step)
})
@@ -1518,7 +1518,7 @@ func HasLocation() predicate.Entity {
return predicate.Entity(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2O, false, LocationTable, LocationColumn),
sqlgraph.Edge(sqlgraph.M2O, false, LocationTable, LocationColumn),
)
sqlgraph.HasNeighbors(s, step)
})

View File

@@ -380,6 +380,21 @@ func (_c *EntityCreate) SetGroup(v *Group) *EntityCreate {
return _c.SetGroupID(v.ID)
}
// AddChildIDs adds the "children" edge to the Entity entity by IDs.
func (_c *EntityCreate) AddChildIDs(ids ...uuid.UUID) *EntityCreate {
_c.mutation.AddChildIDs(ids...)
return _c
}
// AddChildren adds the "children" edges to the Entity entity.
func (_c *EntityCreate) AddChildren(v ...*Entity) *EntityCreate {
ids := make([]uuid.UUID, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddChildIDs(ids...)
}
// SetParentID sets the "parent" edge to the Entity entity by ID.
func (_c *EntityCreate) SetParentID(id uuid.UUID) *EntityCreate {
_c.mutation.SetParentID(id)
@@ -399,38 +414,19 @@ func (_c *EntityCreate) SetParent(v *Entity) *EntityCreate {
return _c.SetParentID(v.ID)
}
// AddChildIDs adds the "children" edge to the Entity entity by IDs.
func (_c *EntityCreate) AddChildIDs(ids ...uuid.UUID) *EntityCreate {
_c.mutation.AddChildIDs(ids...)
// AddEntityIDs adds the "entity" edge to the Entity entity by IDs.
func (_c *EntityCreate) AddEntityIDs(ids ...uuid.UUID) *EntityCreate {
_c.mutation.AddEntityIDs(ids...)
return _c
}
// AddChildren adds the "children" edges to the Entity entity.
func (_c *EntityCreate) AddChildren(v ...*Entity) *EntityCreate {
// AddEntity adds the "entity" edges to the Entity entity.
func (_c *EntityCreate) AddEntity(v ...*Entity) *EntityCreate {
ids := make([]uuid.UUID, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddChildIDs(ids...)
}
// SetEntityID sets the "entity" edge to the Entity entity by ID.
func (_c *EntityCreate) SetEntityID(id uuid.UUID) *EntityCreate {
_c.mutation.SetEntityID(id)
return _c
}
// SetNillableEntityID sets the "entity" edge to the Entity entity by ID if the given value is not nil.
func (_c *EntityCreate) SetNillableEntityID(id *uuid.UUID) *EntityCreate {
if id != nil {
_c = _c.SetEntityID(*id)
}
return _c
}
// SetEntity sets the "entity" edge to the Entity entity.
func (_c *EntityCreate) SetEntity(v *Entity) *EntityCreate {
return _c.SetEntityID(v.ID)
return _c.AddEntityIDs(ids...)
}
// SetLocationID sets the "location" edge to the Entity entity by ID.
@@ -843,27 +839,10 @@ func (_c *EntityCreate) createSpec() (*Entity, *sqlgraph.CreateSpec) {
_node.group_entities = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.ParentIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: entity.ParentTable,
Columns: []string{entity.ParentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.entity_children = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.ChildrenIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Inverse: true,
Table: entity.ChildrenTable,
Columns: []string{entity.ChildrenColumn},
Bidi: false,
@@ -876,9 +855,26 @@ func (_c *EntityCreate) createSpec() (*Entity, *sqlgraph.CreateSpec) {
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.ParentIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: entity.ParentTable,
Columns: []string{entity.ParentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.entity_parent = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.EntityIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Rel: sqlgraph.O2M,
Inverse: true,
Table: entity.EntityTable,
Columns: []string{entity.EntityColumn},
@@ -890,12 +886,11 @@ func (_c *EntityCreate) createSpec() (*Entity, *sqlgraph.CreateSpec) {
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.entity_location = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.LocationIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Rel: sqlgraph.M2O,
Inverse: false,
Table: entity.LocationTable,
Columns: []string{entity.LocationColumn},
@@ -907,6 +902,7 @@ func (_c *EntityCreate) createSpec() (*Entity, *sqlgraph.CreateSpec) {
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.entity_location = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.LabelIDs(); len(nodes) > 0 {

View File

@@ -31,8 +31,8 @@ type EntityQuery struct {
inters []Interceptor
predicates []predicate.Entity
withGroup *GroupQuery
withParent *EntityQuery
withChildren *EntityQuery
withParent *EntityQuery
withEntity *EntityQuery
withLocation *EntityQuery
withLabel *LabelQuery
@@ -99,28 +99,6 @@ func (_q *EntityQuery) QueryGroup() *GroupQuery {
return query
}
// QueryParent chains the current query on the "parent" edge.
func (_q *EntityQuery) QueryParent() *EntityQuery {
query := (&EntityClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(entity.Table, entity.FieldID, selector),
sqlgraph.To(entity.Table, entity.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, entity.ParentTable, entity.ParentColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryChildren chains the current query on the "children" edge.
func (_q *EntityQuery) QueryChildren() *EntityQuery {
query := (&EntityClient{config: _q.config}).Query()
@@ -135,7 +113,29 @@ func (_q *EntityQuery) QueryChildren() *EntityQuery {
step := sqlgraph.NewStep(
sqlgraph.From(entity.Table, entity.FieldID, selector),
sqlgraph.To(entity.Table, entity.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, entity.ChildrenTable, entity.ChildrenColumn),
sqlgraph.Edge(sqlgraph.O2M, true, entity.ChildrenTable, entity.ChildrenColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryParent chains the current query on the "parent" edge.
func (_q *EntityQuery) QueryParent() *EntityQuery {
query := (&EntityClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(entity.Table, entity.FieldID, selector),
sqlgraph.To(entity.Table, entity.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, entity.ParentTable, entity.ParentColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
@@ -157,7 +157,7 @@ func (_q *EntityQuery) QueryEntity() *EntityQuery {
step := sqlgraph.NewStep(
sqlgraph.From(entity.Table, entity.FieldID, selector),
sqlgraph.To(entity.Table, entity.FieldID),
sqlgraph.Edge(sqlgraph.O2O, true, entity.EntityTable, entity.EntityColumn),
sqlgraph.Edge(sqlgraph.O2M, true, entity.EntityTable, entity.EntityColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
@@ -179,7 +179,7 @@ func (_q *EntityQuery) QueryLocation() *EntityQuery {
step := sqlgraph.NewStep(
sqlgraph.From(entity.Table, entity.FieldID, selector),
sqlgraph.To(entity.Table, entity.FieldID),
sqlgraph.Edge(sqlgraph.O2O, false, entity.LocationTable, entity.LocationColumn),
sqlgraph.Edge(sqlgraph.M2O, false, entity.LocationTable, entity.LocationColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
@@ -490,8 +490,8 @@ func (_q *EntityQuery) Clone() *EntityQuery {
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Entity{}, _q.predicates...),
withGroup: _q.withGroup.Clone(),
withParent: _q.withParent.Clone(),
withChildren: _q.withChildren.Clone(),
withParent: _q.withParent.Clone(),
withEntity: _q.withEntity.Clone(),
withLocation: _q.withLocation.Clone(),
withLabel: _q.withLabel.Clone(),
@@ -516,17 +516,6 @@ func (_q *EntityQuery) WithGroup(opts ...func(*GroupQuery)) *EntityQuery {
return _q
}
// WithParent tells the query-builder to eager-load the nodes that are connected to
// the "parent" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *EntityQuery) WithParent(opts ...func(*EntityQuery)) *EntityQuery {
query := (&EntityClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withParent = query
return _q
}
// WithChildren tells the query-builder to eager-load the nodes that are connected to
// the "children" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *EntityQuery) WithChildren(opts ...func(*EntityQuery)) *EntityQuery {
@@ -538,6 +527,17 @@ func (_q *EntityQuery) WithChildren(opts ...func(*EntityQuery)) *EntityQuery {
return _q
}
// WithParent tells the query-builder to eager-load the nodes that are connected to
// the "parent" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *EntityQuery) WithParent(opts ...func(*EntityQuery)) *EntityQuery {
query := (&EntityClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withParent = query
return _q
}
// WithEntity tells the query-builder to eager-load the nodes that are connected to
// the "entity" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *EntityQuery) WithEntity(opts ...func(*EntityQuery)) *EntityQuery {
@@ -696,8 +696,8 @@ func (_q *EntityQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Entit
_spec = _q.querySpec()
loadedTypes = [10]bool{
_q.withGroup != nil,
_q.withParent != nil,
_q.withChildren != nil,
_q.withParent != nil,
_q.withEntity != nil,
_q.withLocation != nil,
_q.withLabel != nil,
@@ -707,7 +707,7 @@ func (_q *EntityQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Entit
_q.withAttachments != nil,
}
)
if _q.withGroup != nil || _q.withParent != nil || _q.withEntity != nil || _q.withType != nil {
if _q.withGroup != nil || _q.withParent != nil || _q.withLocation != nil || _q.withType != nil {
withFKs = true
}
if withFKs {
@@ -737,12 +737,6 @@ func (_q *EntityQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Entit
return nil, err
}
}
if query := _q.withParent; query != nil {
if err := _q.loadParent(ctx, query, nodes, nil,
func(n *Entity, e *Entity) { n.Edges.Parent = e }); err != nil {
return nil, err
}
}
if query := _q.withChildren; query != nil {
if err := _q.loadChildren(ctx, query, nodes,
func(n *Entity) { n.Edges.Children = []*Entity{} },
@@ -750,9 +744,16 @@ func (_q *EntityQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Entit
return nil, err
}
}
if query := _q.withParent; query != nil {
if err := _q.loadParent(ctx, query, nodes, nil,
func(n *Entity, e *Entity) { n.Edges.Parent = e }); err != nil {
return nil, err
}
}
if query := _q.withEntity; query != nil {
if err := _q.loadEntity(ctx, query, nodes, nil,
func(n *Entity, e *Entity) { n.Edges.Entity = e }); err != nil {
if err := _q.loadEntity(ctx, query, nodes,
func(n *Entity) { n.Edges.Entity = []*Entity{} },
func(n *Entity, e *Entity) { n.Edges.Entity = append(n.Edges.Entity, e) }); err != nil {
return nil, err
}
}
@@ -833,38 +834,6 @@ func (_q *EntityQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes [
}
return nil
}
func (_q *EntityQuery) loadParent(ctx context.Context, query *EntityQuery, nodes []*Entity, init func(*Entity), assign func(*Entity, *Entity)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Entity)
for i := range nodes {
if nodes[i].entity_children == nil {
continue
}
fk := *nodes[i].entity_children
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(entity.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "entity_children" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *EntityQuery) loadChildren(ctx context.Context, query *EntityQuery, nodes []*Entity, init func(*Entity), assign func(*Entity, *Entity)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Entity)
@@ -884,19 +853,82 @@ func (_q *EntityQuery) loadChildren(ctx context.Context, query *EntityQuery, nod
return err
}
for _, n := range neighbors {
fk := n.entity_children
fk := n.entity_parent
if fk == nil {
return fmt.Errorf(`foreign-key "entity_children" is nil for node %v`, n.ID)
return fmt.Errorf(`foreign-key "entity_parent" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "entity_children" returned %v for node %v`, *fk, n.ID)
return fmt.Errorf(`unexpected referenced foreign-key "entity_parent" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (_q *EntityQuery) loadParent(ctx context.Context, query *EntityQuery, nodes []*Entity, init func(*Entity), assign func(*Entity, *Entity)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Entity)
for i := range nodes {
if nodes[i].entity_parent == nil {
continue
}
fk := *nodes[i].entity_parent
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(entity.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "entity_parent" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *EntityQuery) loadEntity(ctx context.Context, query *EntityQuery, nodes []*Entity, init func(*Entity), assign func(*Entity, *Entity)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Entity)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Entity(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(entity.EntityColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.entity_location
if fk == nil {
return fmt.Errorf(`foreign-key "entity_location" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "entity_location" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (_q *EntityQuery) loadLocation(ctx context.Context, query *EntityQuery, nodes []*Entity, init func(*Entity), assign func(*Entity, *Entity)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Entity)
for i := range nodes {
@@ -928,34 +960,6 @@ func (_q *EntityQuery) loadEntity(ctx context.Context, query *EntityQuery, nodes
}
return nil
}
func (_q *EntityQuery) loadLocation(ctx context.Context, query *EntityQuery, nodes []*Entity, init func(*Entity), assign func(*Entity, *Entity)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Entity)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
}
query.withFKs = true
query.Where(predicate.Entity(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(entity.LocationColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.entity_location
if fk == nil {
return fmt.Errorf(`foreign-key "entity_location" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "entity_location" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (_q *EntityQuery) loadLabel(ctx context.Context, query *LabelQuery, nodes []*Entity, init func(*Entity), assign func(*Entity, *Label)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[uuid.UUID]*Entity)

View File

@@ -466,6 +466,21 @@ func (_u *EntityUpdate) SetGroup(v *Group) *EntityUpdate {
return _u.SetGroupID(v.ID)
}
// AddChildIDs adds the "children" edge to the Entity entity by IDs.
func (_u *EntityUpdate) AddChildIDs(ids ...uuid.UUID) *EntityUpdate {
_u.mutation.AddChildIDs(ids...)
return _u
}
// AddChildren adds the "children" edges to the Entity entity.
func (_u *EntityUpdate) AddChildren(v ...*Entity) *EntityUpdate {
ids := make([]uuid.UUID, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddChildIDs(ids...)
}
// SetParentID sets the "parent" edge to the Entity entity by ID.
func (_u *EntityUpdate) SetParentID(id uuid.UUID) *EntityUpdate {
_u.mutation.SetParentID(id)
@@ -485,38 +500,19 @@ func (_u *EntityUpdate) SetParent(v *Entity) *EntityUpdate {
return _u.SetParentID(v.ID)
}
// AddChildIDs adds the "children" edge to the Entity entity by IDs.
func (_u *EntityUpdate) AddChildIDs(ids ...uuid.UUID) *EntityUpdate {
_u.mutation.AddChildIDs(ids...)
// AddEntityIDs adds the "entity" edge to the Entity entity by IDs.
func (_u *EntityUpdate) AddEntityIDs(ids ...uuid.UUID) *EntityUpdate {
_u.mutation.AddEntityIDs(ids...)
return _u
}
// AddChildren adds the "children" edges to the Entity entity.
func (_u *EntityUpdate) AddChildren(v ...*Entity) *EntityUpdate {
// AddEntity adds the "entity" edges to the Entity entity.
func (_u *EntityUpdate) AddEntity(v ...*Entity) *EntityUpdate {
ids := make([]uuid.UUID, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddChildIDs(ids...)
}
// SetEntityID sets the "entity" edge to the Entity entity by ID.
func (_u *EntityUpdate) SetEntityID(id uuid.UUID) *EntityUpdate {
_u.mutation.SetEntityID(id)
return _u
}
// SetNillableEntityID sets the "entity" edge to the Entity entity by ID if the given value is not nil.
func (_u *EntityUpdate) SetNillableEntityID(id *uuid.UUID) *EntityUpdate {
if id != nil {
_u = _u.SetEntityID(*id)
}
return _u
}
// SetEntity sets the "entity" edge to the Entity entity.
func (_u *EntityUpdate) SetEntity(v *Entity) *EntityUpdate {
return _u.SetEntityID(v.ID)
return _u.AddEntityIDs(ids...)
}
// SetLocationID sets the "location" edge to the Entity entity by ID.
@@ -628,12 +624,6 @@ func (_u *EntityUpdate) ClearGroup() *EntityUpdate {
return _u
}
// ClearParent clears the "parent" edge to the Entity entity.
func (_u *EntityUpdate) ClearParent() *EntityUpdate {
_u.mutation.ClearParent()
return _u
}
// ClearChildren clears all "children" edges to the Entity entity.
func (_u *EntityUpdate) ClearChildren() *EntityUpdate {
_u.mutation.ClearChildren()
@@ -655,12 +645,33 @@ func (_u *EntityUpdate) RemoveChildren(v ...*Entity) *EntityUpdate {
return _u.RemoveChildIDs(ids...)
}
// ClearEntity clears the "entity" edge to the Entity entity.
// ClearParent clears the "parent" edge to the Entity entity.
func (_u *EntityUpdate) ClearParent() *EntityUpdate {
_u.mutation.ClearParent()
return _u
}
// ClearEntity clears all "entity" edges to the Entity entity.
func (_u *EntityUpdate) ClearEntity() *EntityUpdate {
_u.mutation.ClearEntity()
return _u
}
// RemoveEntityIDs removes the "entity" edge to Entity entities by IDs.
func (_u *EntityUpdate) RemoveEntityIDs(ids ...uuid.UUID) *EntityUpdate {
_u.mutation.RemoveEntityIDs(ids...)
return _u
}
// RemoveEntity removes "entity" edges to Entity entities.
func (_u *EntityUpdate) RemoveEntity(v ...*Entity) *EntityUpdate {
ids := make([]uuid.UUID, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveEntityIDs(ids...)
}
// ClearLocation clears the "location" edge to the Entity entity.
func (_u *EntityUpdate) ClearLocation() *EntityUpdate {
_u.mutation.ClearLocation()
@@ -1007,39 +1018,10 @@ func (_u *EntityUpdate) sqlSave(ctx context.Context) (_node int, err error) {
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.ParentCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: entity.ParentTable,
Columns: []string{entity.ParentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.ParentIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: entity.ParentTable,
Columns: []string{entity.ParentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.ChildrenCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Inverse: true,
Table: entity.ChildrenTable,
Columns: []string{entity.ChildrenColumn},
Bidi: false,
@@ -1052,7 +1034,7 @@ func (_u *EntityUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if nodes := _u.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !_u.mutation.ChildrenCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Inverse: true,
Table: entity.ChildrenTable,
Columns: []string{entity.ChildrenColumn},
Bidi: false,
@@ -1068,7 +1050,7 @@ func (_u *EntityUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if nodes := _u.mutation.ChildrenIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Inverse: true,
Table: entity.ChildrenTable,
Columns: []string{entity.ChildrenColumn},
Bidi: false,
@@ -1081,9 +1063,38 @@ func (_u *EntityUpdate) sqlSave(ctx context.Context) (_node int, err error) {
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.ParentCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: entity.ParentTable,
Columns: []string{entity.ParentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.ParentIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: entity.ParentTable,
Columns: []string{entity.ParentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.EntityCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Rel: sqlgraph.O2M,
Inverse: true,
Table: entity.EntityTable,
Columns: []string{entity.EntityColumn},
@@ -1094,9 +1105,25 @@ func (_u *EntityUpdate) sqlSave(ctx context.Context) (_node int, err error) {
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedEntityIDs(); len(nodes) > 0 && !_u.mutation.EntityCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: entity.EntityTable,
Columns: []string{entity.EntityColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.EntityIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Rel: sqlgraph.O2M,
Inverse: true,
Table: entity.EntityTable,
Columns: []string{entity.EntityColumn},
@@ -1112,7 +1139,7 @@ func (_u *EntityUpdate) sqlSave(ctx context.Context) (_node int, err error) {
}
if _u.mutation.LocationCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Rel: sqlgraph.M2O,
Inverse: false,
Table: entity.LocationTable,
Columns: []string{entity.LocationColumn},
@@ -1125,7 +1152,7 @@ func (_u *EntityUpdate) sqlSave(ctx context.Context) (_node int, err error) {
}
if nodes := _u.mutation.LocationIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Rel: sqlgraph.M2O,
Inverse: false,
Table: entity.LocationTable,
Columns: []string{entity.LocationColumn},
@@ -1799,6 +1826,21 @@ func (_u *EntityUpdateOne) SetGroup(v *Group) *EntityUpdateOne {
return _u.SetGroupID(v.ID)
}
// AddChildIDs adds the "children" edge to the Entity entity by IDs.
func (_u *EntityUpdateOne) AddChildIDs(ids ...uuid.UUID) *EntityUpdateOne {
_u.mutation.AddChildIDs(ids...)
return _u
}
// AddChildren adds the "children" edges to the Entity entity.
func (_u *EntityUpdateOne) AddChildren(v ...*Entity) *EntityUpdateOne {
ids := make([]uuid.UUID, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddChildIDs(ids...)
}
// SetParentID sets the "parent" edge to the Entity entity by ID.
func (_u *EntityUpdateOne) SetParentID(id uuid.UUID) *EntityUpdateOne {
_u.mutation.SetParentID(id)
@@ -1818,38 +1860,19 @@ func (_u *EntityUpdateOne) SetParent(v *Entity) *EntityUpdateOne {
return _u.SetParentID(v.ID)
}
// AddChildIDs adds the "children" edge to the Entity entity by IDs.
func (_u *EntityUpdateOne) AddChildIDs(ids ...uuid.UUID) *EntityUpdateOne {
_u.mutation.AddChildIDs(ids...)
// AddEntityIDs adds the "entity" edge to the Entity entity by IDs.
func (_u *EntityUpdateOne) AddEntityIDs(ids ...uuid.UUID) *EntityUpdateOne {
_u.mutation.AddEntityIDs(ids...)
return _u
}
// AddChildren adds the "children" edges to the Entity entity.
func (_u *EntityUpdateOne) AddChildren(v ...*Entity) *EntityUpdateOne {
// AddEntity adds the "entity" edges to the Entity entity.
func (_u *EntityUpdateOne) AddEntity(v ...*Entity) *EntityUpdateOne {
ids := make([]uuid.UUID, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddChildIDs(ids...)
}
// SetEntityID sets the "entity" edge to the Entity entity by ID.
func (_u *EntityUpdateOne) SetEntityID(id uuid.UUID) *EntityUpdateOne {
_u.mutation.SetEntityID(id)
return _u
}
// SetNillableEntityID sets the "entity" edge to the Entity entity by ID if the given value is not nil.
func (_u *EntityUpdateOne) SetNillableEntityID(id *uuid.UUID) *EntityUpdateOne {
if id != nil {
_u = _u.SetEntityID(*id)
}
return _u
}
// SetEntity sets the "entity" edge to the Entity entity.
func (_u *EntityUpdateOne) SetEntity(v *Entity) *EntityUpdateOne {
return _u.SetEntityID(v.ID)
return _u.AddEntityIDs(ids...)
}
// SetLocationID sets the "location" edge to the Entity entity by ID.
@@ -1961,12 +1984,6 @@ func (_u *EntityUpdateOne) ClearGroup() *EntityUpdateOne {
return _u
}
// ClearParent clears the "parent" edge to the Entity entity.
func (_u *EntityUpdateOne) ClearParent() *EntityUpdateOne {
_u.mutation.ClearParent()
return _u
}
// ClearChildren clears all "children" edges to the Entity entity.
func (_u *EntityUpdateOne) ClearChildren() *EntityUpdateOne {
_u.mutation.ClearChildren()
@@ -1988,12 +2005,33 @@ func (_u *EntityUpdateOne) RemoveChildren(v ...*Entity) *EntityUpdateOne {
return _u.RemoveChildIDs(ids...)
}
// ClearEntity clears the "entity" edge to the Entity entity.
// ClearParent clears the "parent" edge to the Entity entity.
func (_u *EntityUpdateOne) ClearParent() *EntityUpdateOne {
_u.mutation.ClearParent()
return _u
}
// ClearEntity clears all "entity" edges to the Entity entity.
func (_u *EntityUpdateOne) ClearEntity() *EntityUpdateOne {
_u.mutation.ClearEntity()
return _u
}
// RemoveEntityIDs removes the "entity" edge to Entity entities by IDs.
func (_u *EntityUpdateOne) RemoveEntityIDs(ids ...uuid.UUID) *EntityUpdateOne {
_u.mutation.RemoveEntityIDs(ids...)
return _u
}
// RemoveEntity removes "entity" edges to Entity entities.
func (_u *EntityUpdateOne) RemoveEntity(v ...*Entity) *EntityUpdateOne {
ids := make([]uuid.UUID, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveEntityIDs(ids...)
}
// ClearLocation clears the "location" edge to the Entity entity.
func (_u *EntityUpdateOne) ClearLocation() *EntityUpdateOne {
_u.mutation.ClearLocation()
@@ -2370,39 +2408,10 @@ func (_u *EntityUpdateOne) sqlSave(ctx context.Context) (_node *Entity, err erro
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.ParentCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: entity.ParentTable,
Columns: []string{entity.ParentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.ParentIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: entity.ParentTable,
Columns: []string{entity.ParentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.ChildrenCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Inverse: true,
Table: entity.ChildrenTable,
Columns: []string{entity.ChildrenColumn},
Bidi: false,
@@ -2415,7 +2424,7 @@ func (_u *EntityUpdateOne) sqlSave(ctx context.Context) (_node *Entity, err erro
if nodes := _u.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !_u.mutation.ChildrenCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Inverse: true,
Table: entity.ChildrenTable,
Columns: []string{entity.ChildrenColumn},
Bidi: false,
@@ -2431,7 +2440,7 @@ func (_u *EntityUpdateOne) sqlSave(ctx context.Context) (_node *Entity, err erro
if nodes := _u.mutation.ChildrenIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Inverse: true,
Table: entity.ChildrenTable,
Columns: []string{entity.ChildrenColumn},
Bidi: false,
@@ -2444,9 +2453,38 @@ func (_u *EntityUpdateOne) sqlSave(ctx context.Context) (_node *Entity, err erro
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.ParentCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: entity.ParentTable,
Columns: []string{entity.ParentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.ParentIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: entity.ParentTable,
Columns: []string{entity.ParentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.EntityCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Rel: sqlgraph.O2M,
Inverse: true,
Table: entity.EntityTable,
Columns: []string{entity.EntityColumn},
@@ -2457,9 +2495,25 @@ func (_u *EntityUpdateOne) sqlSave(ctx context.Context) (_node *Entity, err erro
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedEntityIDs(); len(nodes) > 0 && !_u.mutation.EntityCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: entity.EntityTable,
Columns: []string{entity.EntityColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(entity.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.EntityIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Rel: sqlgraph.O2M,
Inverse: true,
Table: entity.EntityTable,
Columns: []string{entity.EntityColumn},
@@ -2475,7 +2529,7 @@ func (_u *EntityUpdateOne) sqlSave(ctx context.Context) (_node *Entity, err erro
}
if _u.mutation.LocationCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Rel: sqlgraph.M2O,
Inverse: false,
Table: entity.LocationTable,
Columns: []string{entity.LocationColumn},
@@ -2488,7 +2542,7 @@ func (_u *EntityUpdateOne) sqlSave(ctx context.Context) (_node *Entity, err erro
}
if nodes := _u.mutation.LocationIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2O,
Rel: sqlgraph.M2O,
Inverse: false,
Table: entity.LocationTable,
Columns: []string{entity.LocationColumn},

View File

@@ -118,8 +118,8 @@ var (
{Name: "sold_to", Type: field.TypeString, Nullable: true},
{Name: "sold_price", Type: field.TypeFloat64, Default: 0},
{Name: "sold_notes", Type: field.TypeString, Nullable: true, Size: 1000},
{Name: "entity_children", Type: field.TypeUUID, Nullable: true},
{Name: "entity_location", Type: field.TypeUUID, Unique: true, Nullable: true},
{Name: "entity_parent", Type: field.TypeUUID, Nullable: true},
{Name: "entity_location", Type: field.TypeUUID, Nullable: true},
{Name: "entity_type_entities", Type: field.TypeUUID, Nullable: true},
{Name: "group_entities", Type: field.TypeUUID},
}
@@ -130,7 +130,7 @@ var (
PrimaryKey: []*schema.Column{EntitiesColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "entities_entities_children",
Symbol: "entities_entities_parent",
Columns: []*schema.Column{EntitiesColumns[25]},
RefColumns: []*schema.Column{EntitiesColumns[0]},
OnDelete: schema.SetNull,

View File

@@ -1882,12 +1882,13 @@ type EntityMutation struct {
clearedFields map[string]struct{}
group *uuid.UUID
clearedgroup bool
parent *uuid.UUID
clearedparent bool
children map[uuid.UUID]struct{}
removedchildren map[uuid.UUID]struct{}
clearedchildren bool
entity *uuid.UUID
parent *uuid.UUID
clearedparent bool
entity map[uuid.UUID]struct{}
removedentity map[uuid.UUID]struct{}
clearedentity bool
location *uuid.UUID
clearedlocation bool
@@ -3166,45 +3167,6 @@ func (m *EntityMutation) ResetGroup() {
m.clearedgroup = false
}
// SetParentID sets the "parent" edge to the Entity entity by id.
func (m *EntityMutation) SetParentID(id uuid.UUID) {
m.parent = &id
}
// ClearParent clears the "parent" edge to the Entity entity.
func (m *EntityMutation) ClearParent() {
m.clearedparent = true
}
// ParentCleared reports if the "parent" edge to the Entity entity was cleared.
func (m *EntityMutation) ParentCleared() bool {
return m.clearedparent
}
// ParentID returns the "parent" edge ID in the mutation.
func (m *EntityMutation) ParentID() (id uuid.UUID, exists bool) {
if m.parent != nil {
return *m.parent, true
}
return
}
// ParentIDs returns the "parent" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// ParentID instead. It exists only for internal usage by the builders.
func (m *EntityMutation) ParentIDs() (ids []uuid.UUID) {
if id := m.parent; id != nil {
ids = append(ids, *id)
}
return
}
// ResetParent resets all changes to the "parent" edge.
func (m *EntityMutation) ResetParent() {
m.parent = nil
m.clearedparent = false
}
// AddChildIDs adds the "children" edge to the Entity entity by ids.
func (m *EntityMutation) AddChildIDs(ids ...uuid.UUID) {
if m.children == nil {
@@ -3259,9 +3221,53 @@ func (m *EntityMutation) ResetChildren() {
m.removedchildren = nil
}
// SetEntityID sets the "entity" edge to the Entity entity by id.
func (m *EntityMutation) SetEntityID(id uuid.UUID) {
m.entity = &id
// SetParentID sets the "parent" edge to the Entity entity by id.
func (m *EntityMutation) SetParentID(id uuid.UUID) {
m.parent = &id
}
// ClearParent clears the "parent" edge to the Entity entity.
func (m *EntityMutation) ClearParent() {
m.clearedparent = true
}
// ParentCleared reports if the "parent" edge to the Entity entity was cleared.
func (m *EntityMutation) ParentCleared() bool {
return m.clearedparent
}
// ParentID returns the "parent" edge ID in the mutation.
func (m *EntityMutation) ParentID() (id uuid.UUID, exists bool) {
if m.parent != nil {
return *m.parent, true
}
return
}
// ParentIDs returns the "parent" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// ParentID instead. It exists only for internal usage by the builders.
func (m *EntityMutation) ParentIDs() (ids []uuid.UUID) {
if id := m.parent; id != nil {
ids = append(ids, *id)
}
return
}
// ResetParent resets all changes to the "parent" edge.
func (m *EntityMutation) ResetParent() {
m.parent = nil
m.clearedparent = false
}
// AddEntityIDs adds the "entity" edge to the Entity entity by ids.
func (m *EntityMutation) AddEntityIDs(ids ...uuid.UUID) {
if m.entity == nil {
m.entity = make(map[uuid.UUID]struct{})
}
for i := range ids {
m.entity[ids[i]] = struct{}{}
}
}
// ClearEntity clears the "entity" edge to the Entity entity.
@@ -3274,20 +3280,29 @@ func (m *EntityMutation) EntityCleared() bool {
return m.clearedentity
}
// EntityID returns the "entity" edge ID in the mutation.
func (m *EntityMutation) EntityID() (id uuid.UUID, exists bool) {
if m.entity != nil {
return *m.entity, true
// RemoveEntityIDs removes the "entity" edge to the Entity entity by IDs.
func (m *EntityMutation) RemoveEntityIDs(ids ...uuid.UUID) {
if m.removedentity == nil {
m.removedentity = make(map[uuid.UUID]struct{})
}
for i := range ids {
delete(m.entity, ids[i])
m.removedentity[ids[i]] = struct{}{}
}
}
// RemovedEntity returns the removed IDs of the "entity" edge to the Entity entity.
func (m *EntityMutation) RemovedEntityIDs() (ids []uuid.UUID) {
for id := range m.removedentity {
ids = append(ids, id)
}
return
}
// EntityIDs returns the "entity" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// EntityID instead. It exists only for internal usage by the builders.
func (m *EntityMutation) EntityIDs() (ids []uuid.UUID) {
if id := m.entity; id != nil {
ids = append(ids, *id)
for id := range m.entity {
ids = append(ids, id)
}
return
}
@@ -3296,6 +3311,7 @@ func (m *EntityMutation) EntityIDs() (ids []uuid.UUID) {
func (m *EntityMutation) ResetEntity() {
m.entity = nil
m.clearedentity = false
m.removedentity = nil
}
// SetLocationID sets the "location" edge to the Entity entity by id.
@@ -4252,12 +4268,12 @@ func (m *EntityMutation) AddedEdges() []string {
if m.group != nil {
edges = append(edges, entity.EdgeGroup)
}
if m.parent != nil {
edges = append(edges, entity.EdgeParent)
}
if m.children != nil {
edges = append(edges, entity.EdgeChildren)
}
if m.parent != nil {
edges = append(edges, entity.EdgeParent)
}
if m.entity != nil {
edges = append(edges, entity.EdgeEntity)
}
@@ -4290,20 +4306,22 @@ func (m *EntityMutation) AddedIDs(name string) []ent.Value {
if id := m.group; id != nil {
return []ent.Value{*id}
}
case entity.EdgeParent:
if id := m.parent; id != nil {
return []ent.Value{*id}
}
case entity.EdgeChildren:
ids := make([]ent.Value, 0, len(m.children))
for id := range m.children {
ids = append(ids, id)
}
return ids
case entity.EdgeEntity:
if id := m.entity; id != nil {
case entity.EdgeParent:
if id := m.parent; id != nil {
return []ent.Value{*id}
}
case entity.EdgeEntity:
ids := make([]ent.Value, 0, len(m.entity))
for id := range m.entity {
ids = append(ids, id)
}
return ids
case entity.EdgeLocation:
if id := m.location; id != nil {
return []ent.Value{*id}
@@ -4346,6 +4364,9 @@ func (m *EntityMutation) RemovedEdges() []string {
if m.removedchildren != nil {
edges = append(edges, entity.EdgeChildren)
}
if m.removedentity != nil {
edges = append(edges, entity.EdgeEntity)
}
if m.removedlabel != nil {
edges = append(edges, entity.EdgeLabel)
}
@@ -4371,6 +4392,12 @@ func (m *EntityMutation) RemovedIDs(name string) []ent.Value {
ids = append(ids, id)
}
return ids
case entity.EdgeEntity:
ids := make([]ent.Value, 0, len(m.removedentity))
for id := range m.removedentity {
ids = append(ids, id)
}
return ids
case entity.EdgeLabel:
ids := make([]ent.Value, 0, len(m.removedlabel))
for id := range m.removedlabel {
@@ -4405,12 +4432,12 @@ func (m *EntityMutation) ClearedEdges() []string {
if m.clearedgroup {
edges = append(edges, entity.EdgeGroup)
}
if m.clearedparent {
edges = append(edges, entity.EdgeParent)
}
if m.clearedchildren {
edges = append(edges, entity.EdgeChildren)
}
if m.clearedparent {
edges = append(edges, entity.EdgeParent)
}
if m.clearedentity {
edges = append(edges, entity.EdgeEntity)
}
@@ -4441,10 +4468,10 @@ func (m *EntityMutation) EdgeCleared(name string) bool {
switch name {
case entity.EdgeGroup:
return m.clearedgroup
case entity.EdgeParent:
return m.clearedparent
case entity.EdgeChildren:
return m.clearedchildren
case entity.EdgeParent:
return m.clearedparent
case entity.EdgeEntity:
return m.clearedentity
case entity.EdgeLocation:
@@ -4473,9 +4500,6 @@ func (m *EntityMutation) ClearEdge(name string) error {
case entity.EdgeParent:
m.ClearParent()
return nil
case entity.EdgeEntity:
m.ClearEntity()
return nil
case entity.EdgeLocation:
m.ClearLocation()
return nil
@@ -4493,12 +4517,12 @@ func (m *EntityMutation) ResetEdge(name string) error {
case entity.EdgeGroup:
m.ResetGroup()
return nil
case entity.EdgeParent:
m.ResetParent()
return nil
case entity.EdgeChildren:
m.ResetChildren()
return nil
case entity.EdgeParent:
m.ResetParent()
return nil
case entity.EdgeEntity:
m.ResetEntity()
return nil

View File

@@ -111,13 +111,12 @@ func (Entity) Edges() []ent.Edge {
}
return []ent.Edge{
edge.To("children", Entity.Type).
From("parent").
Unique(),
edge.To("parent", Entity.Type).
Unique().
From("children"),
edge.To("location", Entity.Type).
Unique().
From("entity").
Unique(),
From("entity"),
edge.From("label", Label.Type).
Ref("entities"),
edge.From("type", EntityType.Type).

View File

@@ -0,0 +1,30 @@
package main
import (
"context"
"log"
"os"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent"
_ "github.com/sysadminsmedia/homebox/backend/internal/data/ent/migrate"
_ "github.com/mattn/go-sqlite3"
)
func main() {
client, err := ent.Open("sqlite3", "file?mode=memory&cache=shared&_fk=1")
if err != nil {
log.Fatalf("failed connecting to mysql: %v", err)
}
defer client.Close()
ctx := context.Background()
// Dump migration changes to an SQL script.
f, err := os.Create("migrate.sql")
if err != nil {
log.Fatalf("create migrate file: %v", err)
}
defer f.Close()
if err := client.Schema.WriteTo(ctx, f); err != nil {
log.Fatalf("failed printing schema changes: %v", err)
}
}

View File

@@ -16,21 +16,48 @@ func init() {
}
func Up20250831120023(ctx context.Context, tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, `PRAGMA foreign_keys = OFF;`)
if err != nil {
return fmt.Errorf("failed to disable foreign keys: %w", err)
}
// Create entity_types table
_, err := tx.ExecContext(ctx, `
CREATE TABLE IF NOT EXISTS "entity_types" (
"id" text NOT NULL,
"created_at" datetime NOT NULL,
"updated_at" datetime NOT NULL,
"name" text NOT NULL,
"description" text NULL,
"icon" text NULL,
"color" text NULL,
"is_location" integer NOT NULL DEFAULT 0,
"group_entity_types" text NOT NULL,
PRIMARY KEY ("id"),
FOREIGN KEY ("group_entity_types") REFERENCES "groups" ("id") ON DELETE CASCADE
);
_, err = tx.ExecContext(ctx, `
CREATE TABLE entities (
id uuid NOT NULL,
created_at datetime NOT NULL,
updated_at datetime NOT NULL,
name text NOT NULL,
description text NULL,
import_ref text NULL,
notes text NULL,
quantity integer NOT NULL DEFAULT (1),
insured bool NOT NULL DEFAULT (false),
archived bool NOT NULL DEFAULT (false),
asset_id integer NOT NULL DEFAULT (0),
sync_child_entities_locations bool NOT NULL DEFAULT (false),
serial_number text NULL,
model_number text NULL,
manufacturer text NULL,
lifetime_warranty bool NOT NULL DEFAULT (false),
warranty_expires datetime NULL,
warranty_details text NULL,
purchase_time datetime NULL,
purchase_from text NULL,
purchase_price real NOT NULL DEFAULT (0),
sold_time datetime NULL,
sold_to text NULL,
sold_price real NOT NULL DEFAULT (0),
sold_notes text NULL,
entity_parent uuid NULL,
entity_location uuid NULL,
entity_type_entities uuid NULL,
group_entities uuid NOT NULL,
PRIMARY KEY (id),
CONSTRAINT entities_entities_parent FOREIGN KEY (entity_parent) REFERENCES entities (id) ON DELETE SET NULL,
CONSTRAINT entities_entities_location FOREIGN KEY (entity_location) REFERENCES entities (id) ON DELETE SET NULL,
CONSTRAINT entities_entity_types_entities FOREIGN KEY (entity_type_entities) REFERENCES entity_types (id) ON DELETE SET NULL,
CONSTRAINT entities_groups_entities FOREIGN KEY (group_entities) REFERENCES groups (id) ON DELETE CASCADE);
`)
if err != nil {
return fmt.Errorf("failed to create entity_types table: %w", err)
@@ -38,41 +65,20 @@ func Up20250831120023(ctx context.Context, tx *sql.Tx) error {
// Create entities table
_, err = tx.ExecContext(ctx, `
CREATE TABLE IF NOT EXISTS "entities" (
"id" text NOT NULL,
"created_at" datetime NOT NULL,
"updated_at" datetime NOT NULL,
"name" text NOT NULL,
"description" text NULL,
"import_ref" text NULL,
"notes" text NULL,
"quantity" integer NOT NULL DEFAULT 1,
"insured" integer NOT NULL DEFAULT 0,
"archived" integer NOT NULL DEFAULT 0,
"asset_id" integer NOT NULL DEFAULT 0,
"serial_number" text NULL,
"model_number" text NULL,
"manufacturer" text NULL,
"lifetime_warranty" integer NOT NULL DEFAULT 0,
"warranty_expires" datetime NULL,
"warranty_details" text NULL,
"purchase_time" datetime NULL,
"purchase_from" text NULL,
"purchase_price" real NOT NULL DEFAULT 0,
"sold_time" datetime NULL,
"sold_to" text NULL,
"sold_price" real NOT NULL DEFAULT 0,
"sold_notes" text NULL,
"group_entities" text NOT NULL,
"entity_children" text NULL,
"entity_parent" text NULL,
"entity_type" text NOT NULL,
PRIMARY KEY ("id"),
FOREIGN KEY ("group_entities") REFERENCES "groups" ("id") ON DELETE CASCADE,
FOREIGN KEY ("entity_children") REFERENCES "entities" ("id") ON DELETE SET NULL,
FOREIGN KEY ("entity_parent") REFERENCES "entities" ("id") ON DELETE SET NULL,
FOREIGN KEY ("entity_type") REFERENCES "entity_types" ("id") ON DELETE CASCADE
);
CREATE TABLE entity_types (
id uuid NOT NULL,
created_at datetime NOT NULL,
updated_at datetime NOT NULL,
name text NOT NULL,
description text NULL,
icon text NULL,
color text NULL,
is_location bool NOT NULL DEFAULT (false),
group_entity_types uuid NOT NULL,
PRIMARY KEY (id),
CONSTRAINT entity_types_groups_entity_types FOREIGN KEY (group_entity_types) REFERENCES groups (id) ON DELETE CASCADE);
CREATE INDEX entitytype_name ON entity_types (name);
CREATE INDEX entitytype_is_location ON entity_types (is_location);
`)
if err != nil {
return fmt.Errorf("failed to create entities table: %w", err)
@@ -80,21 +86,23 @@ func Up20250831120023(ctx context.Context, tx *sql.Tx) error {
// Create entity_fields table
_, err = tx.ExecContext(ctx, `
CREATE TABLE IF NOT EXISTS "entity_fields" (
"id" text NOT NULL,
"created_at" datetime NOT NULL,
"updated_at" datetime NOT NULL,
"name" text NOT NULL,
"description" text NULL,
"type" text NOT NULL,
"text_value" text NULL,
"number_value" integer NULL,
"boolean_value" integer NOT NULL DEFAULT 0,
"time_value" datetime NULL,
"entity_fields" text NULL,
PRIMARY KEY ("id"),
FOREIGN KEY ("entity_fields") REFERENCES "entities" ("id") ON DELETE CASCADE
);
CREATE TABLE entity_fields (
id uuid NOT NULL,
created_at datetime NOT NULL,
updated_at datetime NOT NULL,
name text NOT NULL,
description text NULL,
type text NOT NULL,
text_value text NULL,
number_value integer NULL,
boolean_value bool NOT NULL DEFAULT (false),
time_value datetime NOT NULL,
entity_fields uuid NULL,
PRIMARY KEY (id),
CONSTRAINT entity_fields_entities_fields FOREIGN KEY (entity_fields) REFERENCES entities (id) ON DELETE CASCADE);
INSERT INTO entity_fields (id, created_at, updated_at, name, description, type, text_value, number_value, boolean_value, time_value, entity_fields)
SELECT id, created_at, updated_at, name, description, type, text_value, number_value, boolean_value, time_value, item_fields FROM item_fields;
DROP TABLE item_fields;
`)
if err != nil {
return fmt.Errorf("failed to create entity_fields table: %w", err)
@@ -105,7 +113,12 @@ func Up20250831120023(ctx context.Context, tx *sql.Tx) error {
if err != nil {
return fmt.Errorf("failed to query groups: %w", err)
}
defer rows.Close()
defer func(rows *sql.Rows) {
err := rows.Close()
if err != nil {
fmt.Printf("failed to close rows: %v\n", err)
}
}(rows)
// Process each group and create default entity types, and perform migrations that depend on entity types information
for rows.Next() {
@@ -139,7 +152,7 @@ func Up20250831120023(ctx context.Context, tx *sql.Tx) error {
_, err = tx.ExecContext(ctx, `
INSERT INTO "entities" (
"id", "created_at", "updated_at", "name", "description",
"group_entities", "entity_children", "entity_type"
"group_entities", "entity_parent", "entity_type_entities"
)
SELECT
l."id", l."created_at", l."updated_at", l."name", l."description",
@@ -159,7 +172,7 @@ func Up20250831120023(ctx context.Context, tx *sql.Tx) error {
"serial_number", "model_number", "manufacturer", "lifetime_warranty",
"warranty_expires", "warranty_details", "purchase_time", "purchase_from",
"purchase_price", "sold_time", "sold_to", "sold_price", "sold_notes",
"group_entities", "entity_type"
"group_entities", "entity_type_entities"
)
SELECT
i."id", i."created_at", i."updated_at", i."name", i."description",
@@ -188,6 +201,84 @@ func Up20250831120023(ctx context.Context, tx *sql.Tx) error {
}
}
// Convert other tables that reference items or locations to reference entities instead
_, err = tx.ExecContext(ctx, `
CREATE TABLE attachments_tmp (
id uuid NOT NULL,
created_at datetime NOT NULL,
updated_at datetime NOT NULL,
type text NOT NULL DEFAULT ('attachment'),
"primary" bool NOT NULL DEFAULT (false),
title text NOT NULL DEFAULT (''),
path text NOT NULL DEFAULT (''),
mime_type text NOT NULL DEFAULT ('application/octet-stream'),
attachment_thumbnail uuid NULL,
entity_attachments uuid NULL,
PRIMARY KEY (id),
CONSTRAINT attachments_attachments_thumbnail FOREIGN KEY (attachment_thumbnail) REFERENCES attachments (id) ON DELETE SET NULL,
CONSTRAINT attachments_entities_attachments FOREIGN KEY (entity_attachments) REFERENCES entities (id) ON DELETE CASCADE);
INSERT INTO "attachments_tmp" (
"id", "created_at", "updated_at", "type", "primary", "title", "path",
"mime_type", "attachment_thumbnail", "entity_attachments")
SELECT id, created_at, updated_at, type, "primary", title, path, mime_type, attachment_thumbnail, item_attachments FROM attachments;
DROP TABLE attachments;
ALTER TABLE attachments_tmp RENAME TO attachments;
CREATE UNIQUE INDEX attachments_attachment_thumbnail_key ON attachments (attachment_thumbnail);
CREATE INDEX idx_attachments_entity_id ON attachments(entity_attachments);
CREATE INDEX idx_attachments_path ON attachments(path);
CREATE INDEX idx_attachments_thumbnail ON attachments(attachment_thumbnail);
`)
if err != nil {
return fmt.Errorf("failed to migrate attachments to reference entities: %w", err)
}
_, err = tx.ExecContext(ctx, `
CREATE TABLE maintenance_entries_tmp (
id uuid NOT NULL,
created_at datetime NOT NULL,
updated_at datetime NOT NULL,
date datetime NULL,
scheduled_date datetime NULL,
name text NOT NULL,
description text NULL,
cost real NOT NULL DEFAULT (0),
entity_id uuid NOT NULL,
PRIMARY KEY (id),
CONSTRAINT maintenance_entries_entities_maintenance_entries FOREIGN KEY (entity_id) REFERENCES entities(id) ON DELETE CASCADE);
INSERT INTO maintenance_entries_tmp (
"id", "created_at", "updated_at", "date", "scheduled_date", "name",
"description", "cost", "entity_id")
SELECT id, created_at, updated_at, date, scheduled_date, name, description, cost, item_id FROM maintenance_entries;
DROP TABLE maintenance_entries;
ALTER TABLE maintenance_entries_tmp RENAME TO maintenance_entries;
`)
if err != nil {
return fmt.Errorf("failed to migrate maintenance entries to reference entities: %w", err)
}
_, err = tx.ExecContext(ctx, `
CREATE TABLE label_entities (
label_id uuid NOT NULL,
entity_id uuid NOT NULL, PRIMARY KEY (label_id, entity_id),
CONSTRAINT label_entities_label_id FOREIGN KEY (label_id) REFERENCES labels (id) ON DELETE CASCADE,
CONSTRAINT label_entities_entity_id FOREIGN KEY (entity_id) REFERENCES entities (id) ON DELETE CASCADE);
INSERT INTO label_entities (label_id, entity_id)
SELECT label_id, item_id FROM label_items;
DROP TABLE label_items;
`)
if err != nil {
return fmt.Errorf("failed to migrate labels to reference entities: %w", err)
}
// Drop old tables
_, err = tx.ExecContext(ctx, `DROP TABLE IF EXISTS "items"`)
if err != nil {
@@ -199,6 +290,11 @@ func Up20250831120023(ctx context.Context, tx *sql.Tx) error {
return fmt.Errorf("failed to drop locations table: %w", err)
}
_, err = tx.ExecContext(ctx, `PRAGMA foreign_keys = ON;`)
if err != nil {
return fmt.Errorf("failed to enable foreign keys: %w", err)
}
return nil
}

View File

@@ -117,12 +117,12 @@ func (r *LocationRepository) GetAll(ctx context.Context, gid uuid.UUID, filter L
FROM
entities
WHERE
entities.entity_children = entities.id
entities.entity_parent = entities.id
AND entities.archived = false
) as item_count
FROM
entities
JOIN entity_types ON entities.entity_type = entity_types.id
JOIN entity_types ON entities.entity_type_entities = entity_types.id
AND entity_types.is_location = true
WHERE
entities.group_entities = $1 {{ FILTER_CHILDREN }}
@@ -131,7 +131,7 @@ func (r *LocationRepository) GetAll(ctx context.Context, gid uuid.UUID, filter L
`
if filter.FilterChildren {
query = strings.Replace(query, "{{ FILTER_CHILDREN }}", "AND entities.entity_children IS NULL", 1)
query = strings.Replace(query, "{{ FILTER_CHILDREN }}", "AND entities.entity_parent IS NULL", 1)
} else {
query = strings.Replace(query, "{{ FILTER_CHILDREN }}", "", 1)
}
@@ -284,19 +284,19 @@ type ItemPath struct {
func (r *LocationRepository) PathForLoc(ctx context.Context, gid, locID uuid.UUID) ([]ItemPath, error) {
query := `WITH RECURSIVE location_path AS (
SELECT e.id, e.name, e.entity_children
SELECT e.id, e.name, e.entity_parent
FROM entities e
JOIN entity_types et ON e.entity_type = et.id
JOIN entity_types et ON e.entity_type_entities = et.id
WHERE e.id = $1
AND e.group_entities = $2
AND et.is_location = true
UNION ALL
SELECT e.id, e.name, e.entity_children
SELECT e.id, e.name, e.entity_parent
FROM entities e
JOIN entity_types et ON e.entity_type = et.id
JOIN location_path lp ON e.id = lp.entity_children
JOIN entity_types et ON e.entity_type_entities = et.id
JOIN location_path lp ON e.id = lp.entity_parent
WHERE et.is_location = true
)
@@ -339,24 +339,24 @@ func (r *LocationRepository) Tree(ctx context.Context, gid uuid.UUID, tq TreeQue
(
SELECT e.id,
e.NAME,
e.entity_children AS parent_id,
e.entity_parent AS parent_id,
0 AS level,
'location' AS node_type
FROM entities e
JOIN entity_types et ON e.entity_type = et.id
WHERE e.entity_children IS NULL
JOIN entity_types et ON e.entity_type_entities = et.id
WHERE e.entity_parent IS NULL
AND et.is_location = true
AND e.group_entities = $1
UNION ALL
SELECT c.id,
c.NAME,
c.entity_children AS parent_id,
c.entity_parent AS parent_id,
level + 1,
'location' AS node_type
FROM entities c
JOIN entity_types et ON c.entity_type = et.id
JOIN entity_types et ON c.entity_type_entities = et.id
JOIN location_tree p
ON c.entity_children = p.id
ON c.entity_parent = p.id
WHERE et.is_location = true
AND level < 10 -- prevent infinite loop & excessive recursion
){{ WITH_ITEMS }}
@@ -382,27 +382,27 @@ func (r *LocationRepository) Tree(ctx context.Context, gid uuid.UUID, tq TreeQue
(
SELECT e.id,
e.NAME,
e.entity_children as parent_id,
e.entity_parent as parent_id,
0 AS level,
'item' AS node_type
FROM entities e
JOIN entity_types et ON e.entity_type = et.id
WHERE e.entity_children IS NULL
JOIN entity_types et ON e.entity_type_entities = et.id
WHERE e.entity_parent IS NULL
AND et.is_location = false
AND e.entity_children IN (SELECT id FROM location_tree)
AND e.entity_parent IN (SELECT id FROM location_tree)
UNION ALL
SELECT c.id,
c.NAME,
c.entity_children AS parent_id,
c.entity_parent AS parent_id,
level + 1,
'item' AS node_type
FROM entities c
JOIN entity_types et ON c.entity_type = et.id
JOIN entity_types et ON c.entity_type_entities = et.id
JOIN item_tree p
ON c.entity_children = p.id
WHERE c.entity_children IS NOT NULL
ON c.entity_parent = p.id
WHERE c.entity_parent IS NOT NULL
AND et.is_location = false
AND level < 10 -- prevent infinite loop & excessive recursion
)`