Skip to content

Commit

Permalink
Adding Verb method to InsertBuilder
Browse files Browse the repository at this point in the history
Fix #2

Co-authored-by: Henrique Vicente <[email protected]>
Co-authored-by: neokami <[email protected]>
  • Loading branch information
henvic and nightwolfz committed Oct 23, 2022
1 parent e8d3dd8 commit ae9fb56
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
14 changes: 10 additions & 4 deletions insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
// InsertBuilder builds SQL INSERT statements.
type InsertBuilder struct {
prefixes []SQLizer
replace bool
verb string
into string
columns []string
values [][]any
Expand All @@ -21,6 +21,12 @@ type InsertBuilder struct {
selectBuilder *SelectBuilder
}

// Verb to be used for the operation (default: INSERT).
func (b InsertBuilder) Verb(v string) InsertBuilder {
b.verb = v
return b
}

// SQL builds the query into a SQL string and bound args.
func (b InsertBuilder) SQL() (sqlStr string, args []any, err error) {
if b.into == "" {
Expand All @@ -43,10 +49,10 @@ func (b InsertBuilder) SQL() (sqlStr string, args []any, err error) {
sql.WriteString(" ")
}

if !b.replace {
sql.WriteString("INSERT ")
if b.verb != "" {
sql.WriteString(b.verb + " ")
} else {
sql.WriteString("REPLACE ")
sql.WriteString("INSERT ")
}

sql.WriteString("INTO ")
Expand Down
16 changes: 16 additions & 0 deletions insert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,19 @@ func TestInsertBuilderReplace(t *testing.T) {
t.Errorf("expected SQL to be %q, got %q instead", want, sql)
}
}

func TestInsertBuilderVerb(t *testing.T) {
t.Parallel()
b := Insert("table").Verb("REPLACE").Values(1)

want := "REPLACE INTO table VALUES ($1)"

sql, _, err := b.SQL()
if err != nil {
t.Errorf("unexpected error: %v", err)
}

if want != sql {
t.Errorf("expected SQL to be %q, got %q instead", want, sql)
}
}
2 changes: 1 addition & 1 deletion statement.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func Insert(into string) InsertBuilder {
// See InsertBuilder.Into.
func Replace(into string) InsertBuilder {
builder := InsertBuilder{}
builder.replace = true
builder.verb = "REPLACE"
return builder.Into(into)
}

Expand Down

0 comments on commit ae9fb56

Please sign in to comment.