Sqlite subpackage: best practice to create associated data #70
-
Hello there. I'm trying to build an app according to the proposed "wtf" architecture. In your blog post Real World SQL Part 1 you wrote:
This is exactly where I am a bit stuck. Specifically I am wondering how you would create associated data in a given sqlite subpackage service. For example, https://github.com/benbjohnson/wtf/blob/main/sqlite/dial.go#L40 However, how would you implement this if it was about creating associated data? To give a more natural example to talk about, let's assume a relation "Person has many Addresses". What would To make this the example more advanced and introduce an actual "join table" we could say "Person has many Addresses through AddressDetails",
Thank you kindly, luzzi |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi @luzzi8. Good question and sorry for the delay getting back to you. For creation, I would use the helper functions (e.g. func (s *PersonService) CreatePerson(ctx context.Context, person *wtf.Person) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
// Create root person object here.
if err := createPerson(ctx, tx, person); err != nil {
return err
}
// Loop over associated addresses and create them here.
for _, address := range person.Addresses {
address.PersonID = person.ID // associate one-to-many relationship here.
if err := createAddress(ctx, tx, address); err != nil {
return err
}
}
// Go ahead and rebuild associations here so we return an object that's
// consistent with what FindPersonByID() would return.
if err := attachPersonAssociations(ctx, tx, person); err != nil {
return err
}
return tx.Commit()
} |
Beta Was this translation helpful? Give feedback.
Hi @luzzi8. Good question and sorry for the delay getting back to you. For creation, I would use the helper functions (e.g.
createAddress()
) within theCreatePerson()
method: