khue bui
khue bui

Reputation: 1416

Golang UPDATE column with Postgres

Let's say I have a table employments and a struct Employment

type Employment struct {
    ID              int     `json:"id"`
    Created_at      string  `json:"created_at"`
    Updated_at      string  `json:"updated_at"`
    Education       string  `json:"education"`
    Job             string  `json:"job"`
    Position        string  `json:"position"`
    Business_phone  string  `json:"business_phone"`
    Next_payday     string  `json:"next_payday"`
    Employment_type int     `json:"employment_type"`
    Income          float64 `json:"income"`
    Additional      float64 `json:"additional"`
}

User can update their employment, the problem is I don't know which fields user want to update.

So that, I decided to range over input struct to get non nil fields to generate query string, some thing like UPDATE employments SET position=$1, income=$2 WHERE id=$3

This is what I got this time

func FlexibleUpdate(table_name string, str interface{}, cond string, ret string) string {

    query := "UPDATE " + table_name + " SET "
    j := 0
    m := structs.Map(str)

    for i := range m {
        if m[i] != "" && m[i] != 0 && m[i] != 0.0 && {
            j++
            query = query + strings.ToLower(i) + "=$" + strconv.Itoa(j) + ","
        }
    }
    j++

    // adding conditions
    if cond != "" {
        query = query[:len(query)-1] + " WHERE " + cond + "=$" + strconv.Itoa(j)
    }

    // return values
    if ret != "" {
        query = query + " RETURNING " + ret
    }

    return query
}

I don't know how to assign input values to $1, $2, ... to execute query

database.DB.QueryRow(query_string, value_1, value_2, ...)

Let me know if you have any idea or another way to resolve it.

Upvotes: 0

Views: 4151

Answers (1)

mkopriva
mkopriva

Reputation: 38223

Just collect the non-nil values in a slice and then use that slice with ... when executing the query.

var values []interface{}
for i := range m {
    if v := m[i]; v != "" && v != 0 && v != 0.0 && /* you're missing a condition here */{
        j++
        query = query + strings.ToLower(i) + "=$" + strconv.Itoa(j) + ","
        values = append(values, v)
    }
}

// ....

database.DB.QueryRow(query_string, values...)

Upvotes: 2

Related Questions