Skip to content

Commit

Permalink
refs #18. add new method ReplaceInto in InsertBuilder
Browse files Browse the repository at this point in the history
  • Loading branch information
huandu committed Apr 21, 2019
1 parent a9b2a7d commit cd2b98b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
15 changes: 13 additions & 2 deletions insert.go
Expand Up @@ -17,12 +17,14 @@ func NewInsertBuilder() *InsertBuilder {
func newInsertBuilder() *InsertBuilder {
args := &Args{}
return &InsertBuilder{
verb: "INSERT",
args: args,
}
}

// InsertBuilder is a builder to build INSERT.
type InsertBuilder struct {
verb string
table string
cols []string
values [][]string
Expand All @@ -36,6 +38,14 @@ func (ib *InsertBuilder) InsertInto(table string) *InsertBuilder {
return ib
}

// ReplaceInto sets table name and changes the verb of ib to REPLACE.
// REPLACE INTO is a MySQL extension to the SQL standard.
func (ib *InsertBuilder) ReplaceInto(table string) *InsertBuilder {
ib.verb = "REPLACE"
ib.table = Escape(table)
return ib
}

// Cols sets columns in INSERT.
func (ib *InsertBuilder) Cols(col ...string) *InsertBuilder {
ib.cols = EscapeAll(col...)
Expand All @@ -54,7 +64,7 @@ func (ib *InsertBuilder) Values(value ...interface{}) *InsertBuilder {
return ib
}

// String returns the compiled DELETE string.
// String returns the compiled INSERT string.
func (ib *InsertBuilder) String() string {
s, _ := ib.Build()
return s
Expand All @@ -70,7 +80,8 @@ func (ib *InsertBuilder) Build() (sql string, args []interface{}) {
// They can be used in `DB#Query` of package `database/sql` directly.
func (ib *InsertBuilder) BuildWithFlavor(flavor Flavor, initialArg ...interface{}) (sql string, args []interface{}) {
buf := &bytes.Buffer{}
buf.WriteString("INSERT INTO ")
buf.WriteString(ib.verb)
buf.WriteString(" INTO ")
buf.WriteString(ib.table)

if len(ib.cols) > 0 {
Expand Down
16 changes: 16 additions & 0 deletions insert_test.go
Expand Up @@ -22,3 +22,19 @@ func ExampleInsertBuilder() {
// INSERT INTO demo.user (id, name, status, created_at) VALUES (?, ?, ?, UNIX_TIMESTAMP(NOW())), (?, ?, ?, ?)
// [1 Huan Du 1 2 Charmy Liu 1 1234567890]
}

func ExampleInsertBuilder_replaceInto() {
ib := NewInsertBuilder()
ib.ReplaceInto("demo.user")
ib.Cols("id", "name", "status", "created_at")
ib.Values(1, "Huan Du", 1, Raw("UNIX_TIMESTAMP(NOW())"))
ib.Values(2, "Charmy Liu", 1, 1234567890)

sql, args := ib.Build()
fmt.Println(sql)
fmt.Println(args)

// Output:
// REPLACE INTO demo.user (id, name, status, created_at) VALUES (?, ?, ?, UNIX_TIMESTAMP(NOW())), (?, ?, ?, ?)
// [1 Huan Du 1 2 Charmy Liu 1 1234567890]
}

0 comments on commit cd2b98b

Please sign in to comment.