Skip to content
Snippets Groups Projects
Commit 49ce5682db45 authored by Christophe de Vienne's avatar Christophe de Vienne
Browse files

add SQLUpsertColumns

This version of SQLUpsert allows to choose which columns would be inserted,
and which columns would be updated only.
parent d907e7ba0383
No related branches found
No related tags found
No related merge requests found
Pipeline #27651 passed
......@@ -133,5 +133,11 @@
// SQLUpsert generates a squirrel "upsert" statement
func SQLUpsert(m Mapped) squirrel.InsertBuilder {
return SQLUpsertColumns(m, m.Columns(true), m.Columns(false))
}
func SQLUpsertColumns(
m Mapped, insertColumns []string, updateColumns []string,
) squirrel.InsertBuilder {
updateSQL, updateArgs, err := squirrel.
Update(m.Table()).
......@@ -136,6 +142,6 @@
updateSQL, updateArgs, err := squirrel.
Update(m.Table()).
SetMap(ValuesMap(m, m.Columns(false)...)).
SetMap(ValuesMap(m, updateColumns...)).
ToSql()
if err != nil {
panic(err)
......@@ -147,7 +153,6 @@
}
suffix := "ON CONFLICT (" + m.PKeyColumn() + ") DO UPDATE SET " + updateParts[1]
allColumns := m.Columns(true)
q := squirrel.
Insert(m.Table()).
PlaceholderFormat(squirrel.Dollar).
......@@ -151,8 +156,8 @@
q := squirrel.
Insert(m.Table()).
PlaceholderFormat(squirrel.Dollar).
Columns(allColumns...).
Values(m.Values(allColumns...)...).
Columns(insertColumns...).
Values(m.Values(insertColumns...)...).
Suffix(suffix, updateArgs...)
return q
}
......
......@@ -105,6 +105,17 @@
return nil
}
// Upsert upserts a Mapped into the db
func (h *SQLHelper) UpsertColumns(insertColumns, updateColumns []string, instances ...Mapped) error {
for _, instance := range instances {
query := SQLUpsertColumns(instance, insertColumns, updateColumns)
if _, err := h.Exec(query); err != nil {
return err
}
}
return nil
}
// Update updates the given Mapped into the db using their
// pkey as predicate for the where clause
func (h *SQLHelper) Update(instances ...Mapped) error {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment