Created
March 2, 2017 19:21
-
-
Save thwarted/7f788e12e08fe898f2ccb64414b09cac to your computer and use it in GitHub Desktop.
an experimental query builder that might make it easier to create safe SQL using prepared statements w/ support for variable length IN expressions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package qb | |
import ( | |
"fmt" | |
) | |
func placeHolders(howmany int) (s string) { | |
s = "?" | |
for ; howmany > 1; howmany-- { | |
s += ",?" | |
} | |
return | |
} | |
type V struct{ a interface{} } | |
type L []interface{} | |
func BuildSelect(components ...interface{}) (q string, args []interface{}) { | |
for _, c := range components { | |
if xx, ok := c.(string); ok { | |
q += xx + " " | |
} else if x, ok := c.(V); ok { | |
q += "? " | |
args = append(args, interface{}(x.a)) | |
} else if y, ok := c.(L); ok { | |
q += "(" + placeHolders(len(y)) + ")" | |
args = append(args, y...) | |
} | |
} | |
return | |
} | |
func demo() { | |
q, args := BuildSelect(`SELECT`, V{1}, `FROM TABLE WHERE G = `, V{"hello"}, `OR Y IN `, L{999, "888", 777}) | |
fmt.Printf("q=%v\n", q) | |
fmt.Printf("args=%#v\n", args) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment