Skip to content

Commit

Permalink
Merge pull request #1747 from go-pg/fix/default-use-zero
Browse files Browse the repository at this point in the history
Fix default + use_zero insert
  • Loading branch information
vmihailenco authored Sep 26, 2020
2 parents fa6db55 + b66dc98 commit c073c96
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 11 deletions.
2 changes: 1 addition & 1 deletion orm/field.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func (f *Field) hasZeroValue(v reflect.Value, index []int) bool {
}
v = v.Field(idx)
}
return f.NullZero() && f.isZero(v)
return f.isZero(v)
}

func (f *Field) NullZero() bool {
Expand Down
29 changes: 20 additions & 9 deletions orm/insert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,6 @@ type InheritInsertTest struct {
Field2 int
}

type InsertNullTest struct {
F1 int
F2 int `pg:",use_zero"`
F3 int `pg:",pk"`
F4 int `pg:",pk,use_zero"`
}

type InsertDefaultTest struct {
Id int
Value string `pg:"default:hello"`
Expand Down Expand Up @@ -172,10 +165,28 @@ var _ = Describe("Insert", func() {
})

It("supports use_zero tag", func() {
q := NewQuery(nil, &InsertNullTest{})
type InsertZeroTest struct {
F1 int
F2 int `pg:",use_zero"`
F3 int `pg:",pk"`
F4 int `pg:",pk,use_zero"`
}

q := NewQuery(nil, &InsertZeroTest{})

s := insertQueryString(q)
Expect(s).To(Equal(`INSERT INTO "insert_zero_tests" ("f1", "f2", "f3", "f4") VALUES (DEFAULT, 0, DEFAULT, 0) RETURNING "f1", "f3"`))
})

It("supports default with use_zero tag", func() {
type InsertZeroTest struct {
F1 bool `pg:"default:true,use_zero"`
}

q := NewQuery(nil, &InsertZeroTest{})

s := insertQueryString(q)
Expect(s).To(Equal(`INSERT INTO "insert_null_tests" ("f1", "f2", "f3", "f4") VALUES (DEFAULT, 0, DEFAULT, 0) RETURNING "f1", "f3"`))
Expect(s).To(Equal(`INSERT INTO "insert_zero_tests" ("f1") VALUES (DEFAULT) RETURNING "f1"`))
})

It("inserts types.Safe", func() {
Expand Down
2 changes: 1 addition & 1 deletion orm/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ func (q *UpdateQuery) appendSetStruct(fmter QueryFormatter, b []byte, strct refl

pos := len(b)
for _, f := range fields {
if q.omitZero && f.HasZeroValue(strct) {
if q.omitZero && f.NullZero() && f.HasZeroValue(strct) {
continue
}

Expand Down

0 comments on commit c073c96

Please sign in to comment.