Skip to content

Commit 72b9263

Browse files
committed
omitempty bug in InsertRecords
1 parent 8166aa3 commit 72b9263

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

tests/pgkit_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,34 @@ func TestRowsWithBigInt(t *testing.T) {
425425
}
426426
}
427427

428+
func TestSugarInsertRecordsMixedOmit(t *testing.T) {
429+
truncateTable(t, "accounts")
430+
431+
records := []*Account{}
432+
mike := "mike"
433+
var empty *string
434+
records = append(records, &Account{Name: "michael", AltName: &mike})
435+
records = append(records, &Account{Name: "mary", AltName: empty})
436+
437+
// Insert
438+
q1 := DB.SQL.InsertRecords(records) //, "accounts")
439+
qs := make(pgkit.Queries, 0)
440+
qs = append(qs, q1)
441+
_, err := DB.Query.BatchExec(context.Background(), qs)
442+
assert.NoError(t, err)
443+
444+
// Select all
445+
var accounts []*Account
446+
q2 := DB.SQL.Select("*").From("accounts").OrderBy("name")
447+
err = DB.Query.GetAll(context.Background(), q2, &accounts)
448+
assert.NoError(t, err)
449+
assert.Len(t, accounts, 2)
450+
assert.Equal(t, "mary", accounts[0].Name)
451+
assert.Nil(t, accounts[0].AltName)
452+
assert.Equal(t, "michael", accounts[1].Name)
453+
assert.Equal(t, "mike", *accounts[1].AltName)
454+
}
455+
428456
func TestSugarInsertAndSelectMultipleRecords(t *testing.T) {
429457
truncateTable(t, "accounts")
430458

tests/schema_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
type Account struct {
1010
ID int64 `db:"id,omitempty"`
1111
Name string `db:"name"`
12+
AltName *string `db:"alt_name,omitempty"` // can be NULL
1213
Disabled bool `db:"disabled"`
1314
CreatedAt time.Time `db:"created_at,omitempty"` // ,omitempty will rely on postgres DEFAULT
1415
}

tests/testdata/pgkit_test_db.sql

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
CREATE TABLE accounts (
22
id SERIAL PRIMARY KEY,
3-
name VARCHAR(255),
3+
name VARCHAR(255) NOT NULL,
4+
alt_name VARCHAR(255),
45
disabled BOOLEAN,
56
new_column_not_in_code BOOLEAN, -- test for backward-compatible migrations, see https://github.com/goware/pgkit/issues/13
67
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL

0 commit comments

Comments
 (0)