Skip to content

Commit

Permalink
insert select on conflict do update support added (#55)
Browse files Browse the repository at this point in the history
  • Loading branch information
bobrnor authored and doug-martin committed Dec 27, 2017
1 parent f60f7d8 commit 846acc3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
7 changes: 5 additions & 2 deletions dataset_insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func (me *Dataset) toInsertSql(o ConflictExpression, rows ...interface{}) (strin
}
switch rows[0].(type) {
case *Dataset:
return me.insertFromSql(*rows[0].(*Dataset), me.isPrepared)
return me.insertFromSql(*rows[0].(*Dataset), me.isPrepared, o)
}

}
Expand Down Expand Up @@ -202,7 +202,7 @@ func (me *Dataset) insertSql(cols ColumnList, values [][]interface{}, prepared b
}

//Creates an insert statement with values coming from another dataset
func (me *Dataset) insertFromSql(other Dataset, prepared bool) (string, []interface{}, error) {
func (me *Dataset) insertFromSql(other Dataset, prepared bool, c ConflictExpression) (string, []interface{}, error) {
buf := NewSqlBuilder(prepared)
if err := me.adapter.CommonTablesSql(buf, me.clauses.CommonTables); err != nil {
return "", nil, err
Expand All @@ -217,6 +217,9 @@ func (me *Dataset) insertFromSql(other Dataset, prepared bool) (string, []interf
if err := other.selectSqlWriteTo(buf); err != nil {
return "", nil, err
}
if err := me.adapter.OnConflictSql(buf, c); err != nil {
return "", nil, err
}
if me.adapter.SupportsReturn() {
if err := me.adapter.ReturningSql(buf, me.clauses.Returning); err != nil {
return "", nil, err
Expand Down
15 changes: 15 additions & 0 deletions dataset_insert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,21 @@ func (me *datasetTest) TestInsertConflictSql__OnConflictDoUpdateWhere() {
assert.Equal(t, `INSERT INTO "items" ("address", "name") VALUES ('111 Test Addr', 'Test') ON CONFLICT (name) DO UPDATE SET "address"=excluded.address WHERE ("name" = 'Test')`, sql)
}

func (me *datasetTest) TestInsertConflictSqlWithDataset__OnConflictDoUpdateWhere() {
t := me.T()
ds1 := From("items")
type item struct {
Address string `db:"address"`
Name string `db:"name"`
}

ds2 := From("ds2")

sql, _, err := ds1.ToInsertConflictSql(DoUpdate("name", Record{"address": L("excluded.address")}).Where(I("name").Eq("Test")), ds2)
assert.NoError(t, err)
assert.Equal(t, `INSERT INTO "items" SELECT * FROM "ds2" ON CONFLICT (name) DO UPDATE SET "address"=excluded.address WHERE ("name" = 'Test')`, sql)
}

func (me *datasetTest) TestInsertIgnoreSql() {
t := me.T()
ds1 := From("items")
Expand Down

0 comments on commit 846acc3

Please sign in to comment.