diff --git a/database/sql.go b/database/sql.go index db68907bbb423d96b2aa2ea8c6f5d4e960b9389a_ZGF0YWJhc2Uvc3FsLmdv..e174902909bd0e2538f07eb114401342fbe464c8_ZGF0YWJhc2Uvc3FsLmdv 100644 --- a/database/sql.go +++ b/database/sql.go @@ -133,6 +133,32 @@ return q } +// SQLUpsertNoPKey generates a squirrel "upsert" statement +func SQLUpsertNoPKey(keyCols []string, m Mapped) squirrel.InsertBuilder { + updateSQL, updateArgs, err := squirrel. + Update(m.Table()). + SetMap(ValuesMap(m, m.Columns(false)...)). + ToSql() + if err != nil { + panic(err) + } + + updateParts := strings.Split(updateSQL, " SET ") + if len(updateParts) != 2 { + panic("Could not split the UPDATE query: " + updateSQL) //nolint:gosec + } + suffix := "ON CONFLICT (" + strings.Join(keyCols, ",") + ") DO UPDATE SET " + updateParts[1] + + allColumns := m.Columns(false) + q := squirrel. + Insert(m.Table()). + PlaceholderFormat(squirrel.Dollar). + Columns(allColumns...). + Values(m.Values(allColumns...)...). + Suffix(suffix, updateArgs...) + return q +} + // SQLInsert build a Insert statement to insert one or several mapped instances // in the database. All the instances must be of the same actual type func SQLInsert(instances ...Mapped) squirrel.InsertBuilder { diff --git a/database/sql_helper.go b/database/sql_helper.go index db68907bbb423d96b2aa2ea8c6f5d4e960b9389a_ZGF0YWJhc2Uvc3FsX2hlbHBlci5nbw==..e174902909bd0e2538f07eb114401342fbe464c8_ZGF0YWJhc2Uvc3FsX2hlbHBlci5nbw== 100644 --- a/database/sql_helper.go +++ b/database/sql_helper.go @@ -61,6 +61,12 @@ return h.Exec(query) } +// InsertNoPKey inserts a Mapped into the db +func (h *SQLHelper) InsertNoPKey(instances ...Mapped) (sql.Result, error) { + query := SQLInsertNoPKey(instances...) + return h.Exec(query) +} + // Upsert upserts a Mapped into the db func (h *SQLHelper) Upsert(instances ...Mapped) error { for _, instance := range instances { @@ -72,6 +78,17 @@ return nil } +// UpsertNoPKey upserts a Mapped into the db +func (h *SQLHelper) UpsertNoPKey(keyCols []string, instances ...Mapped) error { + for _, instance := range instances { + query := SQLUpsertNoPKey(keyCols, instance) + if _, err := h.Exec(query); err != nil { + return err + } + } + return nil +} + // SyncRelationStrings ... func (h *SQLHelper) SyncRelationStrings( table string, colFrom string, colTo string,