uptrace / bun

SQL-first Golang ORM
https://bun.uptrace.dev
BSD 2-Clause "Simplified" License
3.65k stars 221 forks source link

Omitzero not working with NewUpdate SET #906

Open soheeeeP opened 1 year ago

soheeeeP commented 1 year ago

According to the docs, Omitzero for NewUpdate is to update columns only when it does not contain an empty value. but it seems to work properly only when using a struct object (not working when using theSet method)

type User struct {
    ID                 int64  `bun:",pk,autoincrement"`
    Description        string `bun:"type:text,nullzero,notnull"`
    Count              int64          `bun:"default:0,notnull,nullzero"`
}

Example of a struct object which contains an empty value: it works

updateUser := &model.User{
    ID:          ID,
    Count:              count,
}

if _, err := db.NewUpdate().Model(updateUser).
    OmitZero().WherePK().Returning("*").Exec(ctx); err != nil {
    return nil, err
}

Example of using Set method in order to define fields to update:

var updateUser *model.User
if _, err := db.NewUpdate().Model(&updateUser).
        Set("count = ?", count) 
    OmitZero().WherePK().Returning("*").Exec(ctx); err != nil {
    return nil, err
}

As Golang uses zero value as nil for integer and float, the count field must not be included in the update query but it generates the query like: UPDATE "user" AS "user" SET count = 0 WHERE (id = 'id' ) RETURNING * which seems OmitZero option is not properly applied for the empty integer value.

Is this by design or an issue?