#Unable to read postgres array into a enum

3 messages · Page 1 of 1 (latest)

tired path
#

Im trying to emulate enums with a const of type string, the problem im having is scanning the query result.

First when i try to run i get an error " pq: scanning to model.MuscleType is not implemented; ". I implemented this function, but it didnt work. However, if i dont use a enum emulation, and just straight up use string, it works just fine.

Does anyone has a idea of how i could get this to work?

type MuscleType string

const (
    Chest    MuscleType = "Chest"
    Shoulder            = "Shoulder"
    Back                = "Back"
    Legs                = "Legs"
    Triceps             = "Triceps"
    Biceps              = "Biceps"
)

// function the error was complaining about
func (m *MuscleType) Scan(value interface{}) error {
    if value == nil {
        *m = ""
        return nil
    }

//i tried tweaking between uint8 and string and neither worked.
    if stringValue, ok := value.(uint8); ok {
        *m = MuscleType(stringValue)
        return nil
    }

    return fmt.Errorf("Invalid type for MuscleType")
}

type Exercise struct {
    ID               int64         
    Name             string        
    Muscle           MuscleType   
    AssistantMuscles []MuscleType  
    Equipment        EquipmentType 
}

func (r *ExerciseRepository) SelectAllExercises() ([]*model.Exercise, error) {
    query := "SELECT * FROM exercises"

    rows, err := r.DB.Query(query)
    if err != nil {
        return nil, err
    }

    var exercises []*model.Exercise
    for rows.Next() {
        var exercise model.Exercise
        if err := rows.Scan(&exercise.ID, &exercise.Name, &exercise.Muscle, pq.Array(&exercise.AssistantMuscles), &exercise.Equipment); err != nil {
            return nil, err
        }
        exercises = append(exercises, &exercise)
    }

    return exercises, nil
}
eternal dust
#

Hello.
I'm not 100% sure about my response.
So, Scan is for scanning (obviously) and it's used when you decode a value from the dabatase to your code. You need to implement Value() (driver.Value, error) from the driver.Value interface.
If you have any questions, let me know! gophervictorious

tired path