huandu / go-sqlbuilder

A flexible and powerful SQL string builder library plus a zero-config ORM.
https://pkg.go.dev/github.com/huandu/go-sqlbuilder
MIT License
1.45k stars 122 forks source link

Insert with subselect #132

Closed cemremengu closed 11 months ago

cemremengu commented 1 year ago

What is a good way to implement insert with a select statement?

I create a select builder and then set it inside the insert builder. Trying something like below when building insert:

if ib.sb != nil {
    query, args := ib.sb.Build()
    buf.WriteString(" (")
    buf.WriteString(query)
    buf.WriteString(")")
    println(buf.String())
    initialArg = append(initialArg. args...)
    return ib.args.Compile(buf.String(), initialArg...)
}

However, I am unable to get the args correctly. Somehow placeholders are missing from the final output. Any suggestions?

huandu commented 1 year ago

You can call ib.args.Add(sb) to get a placeholder string holding a reference to SelectBuilder instance. You can then use the placeholder string

Here is a reference implementation for a INSERT INTO ... SELECT builder: https://go.dev/play/p/sWHptqfluAS

cemremengu commented 1 year ago

Thanks this worked like a charm! Would you like me to send a PR for this?

huandu commented 1 year ago

Yes, it's appreciated. Regarding to the INSERT INTO ... SELECT design, it's recommended to extend InsertBuilder rather than add a new builder. We can discuss more details in your PR.