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 authored and lippserd committed May 23, 2024
1 parent cf90a39 commit a016cc2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
7 changes: 7 additions & 0 deletions pkg/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 pkg/database/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,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 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 @@ -322,7 +329,14 @@ func (db *DB) BuildUpsertStmt(subject interface{}) (stmt string, placeholders in
clause = "ON DUPLICATE KEY UPDATE"
setFormat = `"%[1]s" = VALUES("%[1]s")`
case 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 a016cc2

Please sign in to comment.