feat: add platform-collection relationship in platform.FetchCollection()

This commit is contained in:
Alexander Navarro 2024-11-25 19:54:41 -03:00
parent 8af94161ab
commit c1684c8dea
7 changed files with 184 additions and 79 deletions

View file

@ -193,7 +193,7 @@ func (conn *DB) NewPlatform(name string, metadata []byte) (*Platform, error) {
Collections: []*Collection{collection},
}
_, err = conn.addRelationwithTx(tx, platform.Id, &collection_relation{}, collection.Id)
_, err = conn.addRelationwithTx(tx, platform.Id, &collection_has_node{}, collection.Id)
if err != nil {
return err
}
@ -381,15 +381,13 @@ func (conn *DB) addRelationwithTx(
data StandardRelationship,
to int64,
) (*Relationship, error) {
class, metadata, err := data.ToRelationship()
if err != nil {
return nil, err
}
class := data.GetClass()
metadata := data.GetMetadata()
relationship := Relationship{
_conn: conn,
_class: class,
Metadata: metadata,
metadata: metadata,
From: from,
To: to,
}
@ -398,7 +396,7 @@ func (conn *DB) addRelationwithTx(
sql := "INSERT INTO relationships (_class, node_from, node_to, metadata) VALUES ($1, $2, $3, $4) RETURNING node_from, node_to;"
_, err = tx.Exec(sql, relationship._class, relationship.From, relationship.To, metadata)
_, err := tx.Exec(sql, relationship._class, relationship.From, relationship.To, metadata)
if err != nil {
return nil, err
}
@ -518,3 +516,66 @@ func BulkCreateNode[T StandardNode](
return rows.Err()
}
func BulkCreateRelationships[T StandardRelationship](
conn *DB,
relationships []T,
) error {
if len(relationships) == 0 {
return nil
}
tx, err := conn.Connection.Begin()
if err != nil {
return err
}
defer tx.Rollback()
// Build the query dynamically based on number of nodes
valueStrings := make([]string, 0, len(relationships))
valueArgs := make([]interface{}, 0, len(relationships)*3)
for i := range relationships {
n := i * 4
valueStrings = append(
valueStrings,
fmt.Sprintf("($%d, $%d, $%d, $%d) ", n+1, n+2, n+3, n+4),
)
node1, node2 := relationships[i].GetNodes()
class := relationships[i].GetClass()
metadata := relationships[i].GetMetadata()
relationships[i].SetConnection(conn)
if class == "" || node1 <= 0 || node2 <= 0 {
return fmt.Errorf("Invalid relationship: %v, %v, %v", class, node1, node2)
}
valueArgs = append(
valueArgs,
class,
node1,
node2,
metadata,
)
}
sql := fmt.Sprintf(`
INSERT INTO relationships
(_class, node_from, node_to, metadata)
VALUES %s
`, strings.Join(valueStrings, ","))
conn.log(DEBUG, "Bulk creating relationships:", sql, valueArgs)
// Execute and scan returned IDs
_, err = tx.Exec(sql, valueArgs...)
if err != nil {
return fmt.Errorf("bulk insert failed: %w", err)
}
tx.Commit()
return nil
}