Skip to content

Commit 54491de

Browse files
yhabteablippserd
authored andcommitted
Allow to dynamically define type constraint name
1 parent 102481a commit 54491de

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
@@ -259,7 +259,14 @@ func (db *DB) BuildInsertIgnoreStmt(into interface{}) (string, int) {
259259
// MySQL treats UPDATE id = id as a no-op.
260260
clause = fmt.Sprintf(`ON DUPLICATE KEY UPDATE "%s" = "%s"`, columns[0], columns[0])
261261
case PostgreSQL:
262-
clause = fmt.Sprintf("ON CONFLICT ON CONSTRAINT pk_%s DO NOTHING", table)
262+
var constraint string
263+
if constrainter, ok := into.(PgsqlOnConflictConstrainter); ok {
264+
constraint = constrainter.PgsqlOnConflictConstraint()
265+
} else {
266+
constraint = "pk_" + table
267+
}
268+
269+
clause = fmt.Sprintf("ON CONFLICT ON CONSTRAINT %s DO NOTHING", constraint)
263270
}
264271

265272
return fmt.Sprintf(
@@ -322,7 +329,14 @@ func (db *DB) BuildUpsertStmt(subject interface{}) (stmt string, placeholders in
322329
clause = "ON DUPLICATE KEY UPDATE"
323330
setFormat = `"%[1]s" = VALUES("%[1]s")`
324331
case PostgreSQL:
325-
clause = fmt.Sprintf("ON CONFLICT ON CONSTRAINT pk_%s DO UPDATE SET", table)
332+
var constraint string
333+
if constrainter, ok := subject.(PgsqlOnConflictConstrainter); ok {
334+
constraint = constrainter.PgsqlOnConflictConstraint()
335+
} else {
336+
constraint = "pk_" + table
337+
}
338+
339+
clause = fmt.Sprintf("ON CONFLICT ON CONSTRAINT %s DO UPDATE SET", constraint)
326340
setFormat = `"%[1]s" = EXCLUDED."%[1]s"`
327341
}
328342

0 commit comments

Comments
 (0)