Search code examples
gocruddata-access-layergo-gorm

GORM : crud operators in generic way


I try to make a Go DAL and for this i mainly used GORM.

Now I tried to make my DAL as abstract as possible, in order to be able to query many tables.

The problem is that i have to repeat myself for each table struct - reflections of my DB.

Let's get an example:

Here is two struct, one for each table in my database :

type Cad_check_status struct {
    Id int
    Status_code int
    Last_update Timestamp
    Path string
    Ref_num int
    System_code int
}

type Cad_check_errors struct {
    Id int
    check_status int
    error_code Timestamp
}

And here their respective Retrieve functions (one for each, even if their are totaly the same, except for the struct instantiation which is the main problem here):

func StatusRetrieve(db *CDb, keyval map[string]interface{}) ([]byte, error){
    atts :=  []Cad_check_status{} // <===== this is my problem, the only difference between the two functions
    errors := db.Where(keyval).Find(&atts).GetErrors()
    err := HandleDBErrors(errors)
    if err != nil {
        return nil, err
    }
    b, _ := json.Marshal(atts)
    return b, nil
  }

func ErrorsRetrieve(db *CDb, keyval map[string]interface{}) ([]byte, error){
    atts :=  []Cad_check_errors{} // <=== my problem again, the rest is the same
    errors := db.Where(keyval).Find(&atts).GetErrors()
    err := HandleDBErrors(errors)
    if err != nil {
        return nil, err
    }
    b, _ := json.Marshal(atts)
    return b, nil
}

So far, I tried to do something like this :

func Retrieve (tableStruct interface{}, db *CDb, keyval map[string]interface{})([]byte, error) {
    atts :=  []tableStruct{} //<=== but of course this is IMPOSSIBLE ! but you got the idea....
    errors := db.Where(keyval).Find(&atts).GetErrors()
    err := HandleDBErrors(errors)
    if err != nil {
        return nil, err
    }
    b, _ := json.Marshal(atts)
    return b, nil
}

Solution

  • Actually your last sample works just fine if you use it correctly:

    func Retrieve (atts interface{}, db *CDb, keyval map[string]interface{})([]byte, error) {
        errors := db.Where(keyval).Find(atts).GetErrors()
        err := HandleDBErrors(errors)
        if err != nil {
            return nil, err
        }
        b, _ := json.Marshal(atts)
        return b, nil
    }
    
    var values []Cad_check_status
    json,err := Retrieve(&values, db, keyval)