go-pg / pg

Golang ORM with focus on PostgreSQL features and performance
https://pg.uptrace.dev/
BSD 2-Clause "Simplified" License
5.66k stars 404 forks source link

Looking for guidance on shared functionality between models #1551

Open tamoyal opened 4 years ago

tamoyal commented 4 years ago

I would like to implement a some shared functionality across models. For example, a method that looks for one result but does not error if the one result is not found.

func (s *baseStore) FindOneByCondition(condition string, models interface{}) interface{} {
    err := s.connection.Model(&models).Where("?", types.Safe(condition)).Select()
    if err != nil {
        panic(err)
    }

    switch reflect.TypeOf(models).Kind() {
    case reflect.Slice:
        results := reflect.ValueOf(models)
        if results.Len() == 1 {
            return results.Index(0)
        } else {
            return nil
        }
    default:
        panic("Bad type!")
    }
}

The issue with this is pg doesn't know the model type so I get a panicpg: Model(unsupported interface {}). I realize this may be a go limitation but wondering if anyone has a suggestion for implementing this or another way of looking at it. I'd probably rather just have the dupe code than build the query myself which I realize is an alternative.

vmihailenco commented 4 years ago

It should be s.connection.Model(models) and slice should be passed by ptr - FindOneByCondition("", &slice)