Search code examples
gosqlx

How to get corresponding fields when selecting specific columns?


Here is the code:

// User Model
type User struct {
    UserID        int           `db:"user_id"`
    UserNme       string        `db:"user_nme"`
    UserEmail     string        `db:"user_email"`
    UserAddressID sql.NullInt64 `db:"user_address_id"`
}
func (ur *userRepository) FindAll() ([]models.User, error) {
    var users []models.User
    query := "select user_nme from users"
    err := ur.Db.Select(&users, query)
    if err != nil {
        return nil, err
    }
    return users, nil
}

Result:

&[]models.User{models.User{UserID:0, UserNme:"Jay Durgan", UserEmail:"", UserAddressID:sql.NullInt64{Int64:0, Valid:false}}, models.User{UserID:0, UserNme:"Arne Balistreri", UserEmail:"", UserAddressID:sql.NullInt64{Int64:0, Valid:false}}, models.User{UserID:0, UserNme:"Greg Willms", UserEmail:"", UserAddressID:sql.NullInt64{Int64:0, Valid:false}}, models.User{UserID:0, UserNme:"Lady Aisha McLaughlin", UserEmail:"", UserAddressID:sql.NullInt64{Int64:0, Valid:false}}, models.User{UserID:0, UserNme:"Mrs. Phoebe Boyle", UserEmail:"", UserAddressID:sql.NullInt64{Int64:0, Valid:false}}}% 

As you can see, I didn't query user_id, user_email and user_address_id columns, but the result give me these fields with zero value.

So, is there a way only get the fields correspond to the queried columns? Beside, I don't want to write it like this: &user.userNme, &user.xxx, &user.xxx which means write each field and populate it. It's too verbose.

Expected result is: {UserNme: "Jay Durgan"}...


Solution

  • By using struct, you can't.

    The other fields will still be there with it's zero value. The fields are property of the struct so whether you need it or not, whether it stored retrieved value from db operation or not, all the fields will still be there.

    The only solution for your case is by using map, so only value of correspondent fields will be retrieved.

    var users []map[string]interface{}
    query := "select user_nme from users"
    err := ur.Db.Select(&users, query)
    if err != nil {
        return nil, err
    }
    

    Result:

    &[]map[string]interface{}{map[string]interface{}{UserNme:"Jay Durgan"}, ...}