Skip to content

Commit

Permalink
Merge pull request #7 from Icinga/constrainter
Browse files Browse the repository at this point in the history
Allow to dynamically define type constraint name
  • Loading branch information
yhabteab authored Feb 5, 2024
2 parents a39ed01 + 57d05b2 commit f0e227c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
7 changes: 7 additions & 0 deletions database/contracts.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,10 @@ type TableNamer interface {
type Scoper interface {
Scope() any
}

// PgsqlOnConflictConstrainter implements the PgsqlOnConflictConstraint method,
// which returns the primary or unique key constraint name of the PostgreSQL table.
type PgsqlOnConflictConstrainter interface {
// PgsqlOnConflictConstraint returns the primary or unique key constraint name of the PostgreSQL table.
PgsqlOnConflictConstraint() string
}
18 changes: 16 additions & 2 deletions database/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,14 @@ func (db *DB) BuildInsertIgnoreStmt(into interface{}) (string, int) {
// MySQL treats UPDATE id = id as a no-op.
clause = fmt.Sprintf(`ON DUPLICATE KEY UPDATE "%s" = "%s"`, columns[0], columns[0])
case driver.PostgreSQL:
clause = fmt.Sprintf("ON CONFLICT ON CONSTRAINT pk_%s DO NOTHING", table)
var constraint string
if constrainter, ok := into.(PgsqlOnConflictConstrainter); ok {
constraint = constrainter.PgsqlOnConflictConstraint()
} else {
constraint = "pk_" + table
}

clause = fmt.Sprintf("ON CONFLICT ON CONSTRAINT %s DO NOTHING", constraint)
}

return fmt.Sprintf(
Expand Down Expand Up @@ -295,7 +302,14 @@ func (db *DB) BuildUpsertStmt(subject interface{}) (stmt string, placeholders in
clause = "ON DUPLICATE KEY UPDATE"
setFormat = `"%[1]s" = VALUES("%[1]s")`
case driver.PostgreSQL:
clause = fmt.Sprintf("ON CONFLICT ON CONSTRAINT pk_%s DO UPDATE SET", table)
var constraint string
if constrainter, ok := subject.(PgsqlOnConflictConstrainter); ok {
constraint = constrainter.PgsqlOnConflictConstraint()
} else {
constraint = "pk_" + table
}

clause = fmt.Sprintf("ON CONFLICT ON CONSTRAINT %s DO UPDATE SET", constraint)
setFormat = `"%[1]s" = EXCLUDED."%[1]s"`
}

Expand Down

0 comments on commit f0e227c

Please sign in to comment.