Skip to content

Commit

Permalink
pgstmt: add on conflict on constraint (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
acoshift committed Jun 16, 2020
1 parent a2becd1 commit ec4c14a
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 3 deletions.
20 changes: 17 additions & 3 deletions pgstmt/insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ type InsertStatement interface {
Values(values ...interface{})
Select(f func(b SelectStatement))
OnConflict(target ...string) OnConflict
OnConflictOnConstraint(constraintName string) OnConflict
Returning(col ...string)
}

Expand Down Expand Up @@ -82,6 +83,11 @@ func (st *insertStmt) OnConflict(target ...string) OnConflict {
return st.conflict
}

func (st *insertStmt) OnConflictOnConstraint(constraintName string) OnConflict {
st.conflict = &conflict{constraint: constraintName}
return st.conflict
}

func (st *insertStmt) Returning(col ...string) {
st.returning.pushString(col...)
}
Expand Down Expand Up @@ -109,8 +115,15 @@ func (st *insertStmt) make() *buffer {
}
if st.conflict != nil {
b.push("on conflict")

// on conflict can be one of
// => ( { index_column_name | ( index_expression ) } [ COLLATE collation ] [ opclass ] [, ...] ) [ WHERE index_predicate ]
// => ON CONSTRAINT constraint_name
if len(st.conflict.targets) > 0 {
b.push(parenString(st.conflict.targets...))
} else if st.conflict.constraint != "" {
b.push("on constraint")
b.push(st.conflict.constraint)
}
if st.conflict.doNothing {
b.push("do nothing")
Expand All @@ -127,9 +140,10 @@ func (st *insertStmt) make() *buffer {
}

type conflict struct {
targets []string
doNothing bool
doUpdate *updateStmt
targets []string
constraint string
doNothing bool
doUpdate *updateStmt
}

func (st *conflict) DoNothing() {
Expand Down
31 changes: 31 additions & 0 deletions pgstmt/insert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,35 @@ func TestInsert(t *testing.T) {
args,
)
})

t.Run("insert on conflict on constraint do update", func(t *testing.T) {
q, args := pgstmt.Insert(func(b pgstmt.InsertStatement) {
b.Into("users")
b.Columns("username", "email")
b.Value("tester1", "tester1@localhost")
b.OnConflictOnConstraint("username_key").DoUpdate(func(b pgstmt.UpdateStatement) {
b.Set("email").ToRaw("excluded.email")
b.Set("updated_at").ToRaw("now()")
})
b.Returning("id")
}).SQL()

assert.Equal(t,
stripSpace(`
insert into users (username, email)
values ($1, $2)
on conflict on constraint username_key do update
set email = excluded.email,
updated_at = now()
returning id
`),
q,
)
assert.EqualValues(t,
[]interface{}{
"tester1", "tester1@localhost",
},
args,
)
})
}

0 comments on commit ec4c14a

Please sign in to comment.