Skip to content

Commit f0e227c

Browse files
authored
Merge pull request #7 from Icinga/constrainter
Allow to dynamically define type constraint name
2 parents a39ed01 + 57d05b2 commit f0e227c

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

database/contracts.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,10 @@ type TableNamer interface {
4747
type Scoper interface {
4848
Scope() any
4949
}
50+
51+
// PgsqlOnConflictConstrainter implements the PgsqlOnConflictConstraint method,
52+
// which returns the primary or unique key constraint name of the PostgreSQL table.
53+
type PgsqlOnConflictConstrainter interface {
54+
// PgsqlOnConflictConstraint returns the primary or unique key constraint name of the PostgreSQL table.
55+
PgsqlOnConflictConstraint() string
56+
}

database/db.go

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,14 @@ func (db *DB) BuildInsertIgnoreStmt(into interface{}) (string, int) {
232232
// MySQL treats UPDATE id = id as a no-op.
233233
clause = fmt.Sprintf(`ON DUPLICATE KEY UPDATE "%s" = "%s"`, columns[0], columns[0])
234234
case driver.PostgreSQL:
235-
clause = fmt.Sprintf("ON CONFLICT ON CONSTRAINT pk_%s DO NOTHING", table)
235+
var constraint string
236+
if constrainter, ok := into.(PgsqlOnConflictConstrainter); ok {
237+
constraint = constrainter.PgsqlOnConflictConstraint()
238+
} else {
239+
constraint = "pk_" + table
240+
}
241+
242+
clause = fmt.Sprintf("ON CONFLICT ON CONSTRAINT %s DO NOTHING", constraint)
236243
}
237244

238245
return fmt.Sprintf(
@@ -295,7 +302,14 @@ func (db *DB) BuildUpsertStmt(subject interface{}) (stmt string, placeholders in
295302
clause = "ON DUPLICATE KEY UPDATE"
296303
setFormat = `"%[1]s" = VALUES("%[1]s")`
297304
case driver.PostgreSQL:
298-
clause = fmt.Sprintf("ON CONFLICT ON CONSTRAINT pk_%s DO UPDATE SET", table)
305+
var constraint string
306+
if constrainter, ok := subject.(PgsqlOnConflictConstrainter); ok {
307+
constraint = constrainter.PgsqlOnConflictConstraint()
308+
} else {
309+
constraint = "pk_" + table
310+
}
311+
312+
clause = fmt.Sprintf("ON CONFLICT ON CONSTRAINT %s DO UPDATE SET", constraint)
299313
setFormat = `"%[1]s" = EXCLUDED."%[1]s"`
300314
}
301315

0 commit comments

Comments
 (0)