Skip to content

Commit

Permalink
fix(inserter): ignoring the pk from the inserter (#75)
Browse files Browse the repository at this point in the history
* ignoring the pk from the inserter

* Adding test
  • Loading branch information
Jacobbrewer1 authored Dec 24, 2024
1 parent 54619b9 commit 8155e7b
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
5 changes: 5 additions & 0 deletions inserter/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ func (b *SQLBatch) genBatch(resources []any) {
tag = f.Name
}

tags := strings.Split(tag, patcher.TagOptSeparator)
if slices.Contains(tags, patcher.DBTagPrimaryKey) {
continue
}

b.args = append(b.args, b.getFieldValue(v.Field(i), f))

// if the field is not unique, skip it
Expand Down
31 changes: 31 additions & 0 deletions inserter/sql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,37 @@ func (s *newBatchSuite) TestNewBatch_Success() {
s.Require().Len(b.Args(), 10)
}

func (s *newBatchSuite) TestNewBatch_Success_IgnorePK() {
type temp struct {
ID int `db:"id,pk"`
Name string `db:"name"`
unexported string `db:"unexported"`
}

resources := []any{
&temp{ID: 1, Name: "test"},
&temp{ID: 2, Name: "test2"},
&temp{ID: 3, Name: "test3"},
&temp{ID: 4, Name: "test4"},
&temp{ID: 5, Name: "test5", unexported: "test"},
}

b := NewBatch(resources, WithTable("temp"), WithTagName("db"))

s.Require().Len(b.Fields(), 1)
s.Require().Len(b.Args(), 5)

s.Condition(func() bool {
for _, f := range b.Fields() {
if f == "id" {
return false
}
}

return true
})
}

func (s *newBatchSuite) TestNewBatch_Success_WithPointedFields() {
type temp struct {
ID *int `db:"id"`
Expand Down
1 change: 1 addition & 0 deletions sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

const (
DefaultDbTagName = "db"
DBTagPrimaryKey = "pk"
)

var (
Expand Down

0 comments on commit 8155e7b

Please sign in to comment.