Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions pgstmt/insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ type InsertStatement interface {

OnConflict(f func(b ConflictTarget)) ConflictAction

// OnConflictDoNothing is the shortcut for
// OnConflict(func(b ConflictTarget) {}).DoNothing()
OnConflictDoNothing()

// OnConflictIndex is the shortcut for
// OnConflict(func(b ConflictTarget) {
// b.Index(target...)
Expand Down Expand Up @@ -104,6 +108,14 @@ func (st *insertStmt) OnConflict(f func(b ConflictTarget)) ConflictAction {
return &st.conflict.action
}

func (st *insertStmt) OnConflictDoNothing() {
st.conflict = &conflict{
action: conflictAction{
doNothing: true,
},
}
}

func (st *insertStmt) OnConflictIndex(target ...string) ConflictAction {
return st.OnConflict(func(b ConflictTarget) {
b.Index(target...)
Expand Down
21 changes: 21 additions & 0 deletions pgstmt/insert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,27 @@ func TestInsert(t *testing.T) {
)
})

t.Run("insert on conflict do nothing", func(t *testing.T) {
q, args := pgstmt.Insert(func(b pgstmt.InsertStatement) {
b.Into("users")
b.Columns("username", "name")
b.Value("tester1", "Tester 1")
b.OnConflictDoNothing()
b.Returning("id")
}).SQL()

assert.Equal(t,
"insert into users (username, name) values ($1, $2) on conflict do nothing returning id",
q,
)
assert.EqualValues(t,
[]any{
"tester1", "Tester 1",
},
args,
)
})

t.Run("insert select", func(t *testing.T) {
q, args := pgstmt.Insert(func(b pgstmt.InsertStatement) {
b.Into("films")
Expand Down