Skip to content

Commit

Permalink
Merge pull request #133 from cemremengu/insertselect
Browse files Browse the repository at this point in the history
add subselect builder for insert
  • Loading branch information
huandu committed Nov 20, 2023
2 parents fd93ff9 + 9c1c183 commit eb77f78
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
18 changes: 18 additions & 0 deletions insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const (
insertMarkerAfterInsertInto
insertMarkerAfterCols
insertMarkerAfterValues
insertMarkerAfterSelect
)

// NewInsertBuilder creates a new INSERT builder.
Expand Down Expand Up @@ -40,6 +41,8 @@ type InsertBuilder struct {

injection *injection
marker injectionMarker

sbHolder string
}

var _ Builder = new(InsertBuilder)
Expand Down Expand Up @@ -89,6 +92,13 @@ func (ib *InsertBuilder) Cols(col ...string) *InsertBuilder {
return ib
}

// Select returns a new SelectBuilder to build a SELECT statement inside the INSERT INTO.
func (isb *InsertBuilder) Select(col ...string) *SelectBuilder {
sb := Select(col...)
isb.sbHolder = isb.args.Add(sb)
return sb
}

// Values adds a list of values for a row in INSERT.
func (ib *InsertBuilder) Values(value ...interface{}) *InsertBuilder {
placeholders := make([]string, 0, len(value))
Expand Down Expand Up @@ -167,6 +177,14 @@ func (ib *InsertBuilder) BuildWithFlavor(flavor Flavor, initialArg ...interface{
ib.injection.WriteTo(buf, insertMarkerAfterCols)
}

if ib.sbHolder != "" {
buf.WriteString(" ")
buf.WriteString(ib.sbHolder)

ib.injection.WriteTo(buf, insertMarkerAfterSelect)
return ib.args.CompileWithFlavor(buf.String(), flavor, initialArg...)
}

if len(ib.values) > 0 {
buf.WriteLeadingString("VALUES ")
values := make([]string, 0, len(ib.values))
Expand Down
32 changes: 32 additions & 0 deletions insert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,35 @@ func ExampleInsertBuilder_SQL() {
// /* before */ INSERT INTO demo.user PARTITION (p0) (id, name, status, created_at) /* after cols */ VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE status = ?
// [3 Shawn Du 1 1234567890 1]
}

func ExampleInsertBuilder_subSelect() {
ib := NewInsertBuilder()
ib.InsertInto("demo.user")
ib.Cols("id", "name")
sb := ib.Select("id", "name").From("demo.test")
sb.Where(sb.EQ("id", 1))

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

// Output:
// INSERT INTO demo.user (id, name) SELECT id, name FROM demo.test WHERE id = ?
// [1]
}

func ExampleInsertBuilder_subSelect_oracle() {
ib := Oracle.NewInsertBuilder()
ib.InsertInto("demo.user")
ib.Cols("id", "name")
sb := ib.Select("id", "name").From("demo.test")
sb.Where(sb.EQ("id", 1))

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

// Output:
// INSERT INTO demo.user (id, name) SELECT id, name FROM demo.test WHERE id = :1
// [1]
}

0 comments on commit eb77f78

Please sign in to comment.