Skip to content

Instantly share code, notes, and snippets.

@hauxe
Created June 10, 2018 06:54
Show Gist options
  • Save hauxe/66bacfdf972d681c0e02a6665e736814 to your computer and use it in GitHub Desktop.
Save hauxe/66bacfdf972d681c0e02a6665e736814 to your computer and use it in GitHub Desktop.
crud read function
// Read read data
func (crud *CRUD) Read(data interface{}) (interface{}, error) {
rv := reflect.ValueOf(data)
rv = reflect.Indirect(rv)
pk := rv.Field(crud.Config.pk.index)
if !pk.CanInterface() {
return nil, errors.Errorf("table %s with primary key has wrong interface type",
crud.Config.TableName, crud.Config.pk.index)
}
rows, err := crud.Config.DB.Queryx(crud.Config.sqlCRUDRead, pk.Interface())
if err != nil {
return nil, errors.Wrap(err, "error crud read")
}
defer rows.Close()
if rows.Next() {
obj := crud.Config.Object.Get()
err = rows.StructScan(obj)
if err != nil {
return nil, errors.Wrap(err, "error crud scan")
}
re, err := buildListOfFields(obj, crud.Config.selectedFields)
if err != nil {
return nil, errors.Wrap(err, "error build list of fields")
}
return re, nil
}
return nil, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment