Skip to content

Commit

Permalink
omitempty bug in InsertRecords
Browse files Browse the repository at this point in the history
  • Loading branch information
ScreamingHawk committed Nov 4, 2024
1 parent 8166aa3 commit 72b9263
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
28 changes: 28 additions & 0 deletions tests/pgkit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,34 @@ func TestRowsWithBigInt(t *testing.T) {
}
}

func TestSugarInsertRecordsMixedOmit(t *testing.T) {
truncateTable(t, "accounts")

records := []*Account{}
mike := "mike"
var empty *string
records = append(records, &Account{Name: "michael", AltName: &mike})
records = append(records, &Account{Name: "mary", AltName: empty})

// Insert
q1 := DB.SQL.InsertRecords(records) //, "accounts")
qs := make(pgkit.Queries, 0)
qs = append(qs, q1)
_, err := DB.Query.BatchExec(context.Background(), qs)
assert.NoError(t, err)

// Select all
var accounts []*Account
q2 := DB.SQL.Select("*").From("accounts").OrderBy("name")
err = DB.Query.GetAll(context.Background(), q2, &accounts)
assert.NoError(t, err)
assert.Len(t, accounts, 2)
assert.Equal(t, "mary", accounts[0].Name)
assert.Nil(t, accounts[0].AltName)
assert.Equal(t, "michael", accounts[1].Name)
assert.Equal(t, "mike", *accounts[1].AltName)
}

func TestSugarInsertAndSelectMultipleRecords(t *testing.T) {
truncateTable(t, "accounts")

Expand Down
1 change: 1 addition & 0 deletions tests/schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
type Account struct {
ID int64 `db:"id,omitempty"`
Name string `db:"name"`
AltName *string `db:"alt_name,omitempty"` // can be NULL
Disabled bool `db:"disabled"`
CreatedAt time.Time `db:"created_at,omitempty"` // ,omitempty will rely on postgres DEFAULT
}
Expand Down
3 changes: 2 additions & 1 deletion tests/testdata/pgkit_test_db.sql
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
CREATE TABLE accounts (
id SERIAL PRIMARY KEY,
name VARCHAR(255),
name VARCHAR(255) NOT NULL,
alt_name VARCHAR(255),
disabled BOOLEAN,
new_column_not_in_code BOOLEAN, -- test for backward-compatible migrations, see https://github.com/goware/pgkit/issues/13
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL
Expand Down

0 comments on commit 72b9263

Please sign in to comment.