Skip to content

Commit

Permalink
Allow to dynamically define type constraint name
Browse files Browse the repository at this point in the history
  • Loading branch information
yhabteab committed Jan 22, 2024
1 parent a39ed01 commit 0b9c801
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
6 changes: 6 additions & 0 deletions database/contracts.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,9 @@ type TableNamer interface {
type Scoper interface {
Scope() any
}

// Constrainter implements the Constraint method,
// which returns the PK or unique key constraint name of the table.
type Constrainter interface {
Constraint() string // Constraint returns the PK/UNIQUE key constraint name
}
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.(Constrainter); ok {
constraint = constrainter.Constraint()
} 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.(Constrainter); ok {
constraint = constrainter.Constraint()
} 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 0b9c801

Please sign in to comment.