PROPOSAL: Add another method for deletion
Hi everyone. This is my proposal pull-request.
I'd like an another generated method named by DeleteByModel.
This method removes a single record of assigned obj argument and validly executes some defined gorm's callbacks
Usage
- Define your model design
// example
Model("Dummy", func() {
RendersTo(DummyMedia)
Description("Dummy Model Description")
Field("id", gorma.Integer, func() {
PrimaryKey()
Description("This is the Dummy Model PK field")
})
Field("dummy_name", gorma.String, func() {})
Field("created_at", gorma.Timestamp, func() {})
Field("updated_at", gorma.Timestamp, func() {})
})
- If you will geenerate models by
goagen gen -d=YOUR_PATH --pkg-path=github.com/goadesign/gorma, target model files haveDeleteByModelmethod.
// Delete removes a single record.
func (m *DummyDB) Delete(ctx context.Context, id int) error {
:
}
// *New generated method*
// DeleteByModel removes a single record of assigned model.
// If record is deleted by this method, some defined callbacks of gorm are executed too.
func (m *DummyDB) DeleteByModel(ctx context.Context, obj *Dummy) error {
defer goa.MeasureSince([]string{"goa", "db", "dummy", "deleteByModel"}, time.Now())
err := m.Db.Delete(obj).Error
if err != nil {
goa.LogError(ctx, "error deleting Dummy", "error", err.Error())
return err
}
return nil
}
Example
If record is deleted by DeleteByModel method, some defined gorm's callbacks(including BeforeDelete, AfterDelete) are validly exected too.
An example as follows:
// Define "AfterDelete" gorm's callback
func (d *Dummy) AfterDelete() (err error) {
fmt.Printf("ID = %d", m.ID)
return
}
// Delete using "Delete(ctx, id)" method
m.Delete(ctx, 1) // will display "ID = 0", because receiver of AfterDelete is an empty object
// Delete using new "DeleteByModel(ctx, obj) method
d = m.Get(ctx, 1)
m.DeleteByModel(ctx, d) // will display "ID = 1"
The proposal looks good to me. Could we call the method DeleteModel instead? seems to flow a bit better. Also for the header comment maybe something like the following is a little bit clearer?
// DeleteModel removes a single record given the corresponding model.
// Exisiting gorm deletion callbacks are executed if a record is deleted.
Finally do you think you could add a few tests? thank you!
Thank you for your quick reply!
do you think you could add a few tests?
OK. It's working properly only in our private project. ))
Should I just add tests of DeleteByModel?